在了解前述各種傳遞方式之後,今天就來幾個範例試試:
接收及傳送Model:
流程:
Model:建立一個資料類別。
public class People
{
public string Name{get;set;}
public string Height{get;set;}
}
Controller:先傳值給View,經異動後再由ViewBag接回資料。
public ActionResult PeopleModelBinding()
{
People people = new People(){
Name = "Tom",
Height = 180
};
return View(people);
}
[HttpPost]
public ActionResult Index(People people)
{
ViewBag.Name = people.Name;
ViewBag.Height = people.Height;
return View();
}
View:先接收資料,再異動後傳回Controller,再接收ViewBag的內容後呈現。
@model DemoApp.People
@using(Html.BeginForm()){
<div>
<p>
姓名:@Html.EditorFor(c => c.Name)
</p>
<p>
身高:@Html.EditorFor(c => c.Height)
</p>
<p>
<input type = "submit" value = "送出" />
</p>
</div>
}
@ViewBag.Name
@ViewBag.Height
Controller不接收資料,只把Model傳送到View呈現。
Model:
public class People
{
public string Name{get;set;}
public string Height{get;set;}
}
Controller:接收View傳來的參數,再回傳給View呈現。
public ActionResult Index(People people)
{
ViewBag.Name = people.Name;
ViewBag.Height = people.Height;
return View();
}
View:將填入的參數送出到Controller後,再接收回來呈現。
@using(Html.BeginForm()){
<div>
<p>
姓名:<input type = "text" name = "people.Name" />
</p>
<p>
身高:<input type = "text" name = "people.Height" />
<p>
<input type = "submit" value = "送出" />
</p>
</div>
}
@ViewBag.Name
@ViewBag.Height
複雜型接收及傳送Model:
Model:建立多個資料類別。
public class Student
{
public string Name{get;set;}
public string Height{get;set;}
}
public class Class
{
public string ClassName{get;set;}
}
public class ClassViewModel
{
public Class classroom{get;set;}
public List<Student> student{get;set;}
}
Controller:傳出學生資料,並接收第一筆修改的資料。
public ActionResult Index()
{
ClassViewModel Class = new ClassViewModel();
Class.student = new List<Student>()
{
new Student(){Name = "桃太郞",Height = 160},
new Student(){Name = "鬼王",Height = 180}
};
Class.classroom = new Class(){className = "空大博士班"};
return View(Class);
}
[HttpPost]
public ActionResult Index(ClassViewModel Class)
{
var FirstPeople = Class.student.FirstOrDefault();
if(FirstPeople != default(Student))
{
ViewBag.Name = FirstPeople.Name;
ViewBag.Height = FirstPeople.Height;
}
return View(Class);
}
View:將填入的參數送出到Controller後,再接收回來呈現。
@model DemoMvcApp.ClassViewModel
@using(Html.BeginForm()){
<div>
<p>班級名稱:@Html.EditorFor(m => m.classroom.ClassName)</p>
<p>學生們</p>
<table>
<tr>
<td>名字</td>
<td>身高</td>
</tr>
@for(int I = 0;I < Model.Student.Count;i++){
<tr>
<td>@Html.EditorFor(m => m.student[i].Name)</td>
<td>@Html.EditorFor(m => m.student[i].Height)</td>
</tr>
}
</table>
<p><input type = "submit" value = "送出" /></p>
</div>
}
@ViewBag.Name
@ViewBag.Height
好的,今天就先到這兒,明天再來繼續吧!