您可以为此使用 EditorTemplates。下面的示例显示了普通表单发布示例。如果需要,您可以使用 serialize 方法并发送表单值来对其进行 ajaxify。
假设您需要编辑课程的学生姓名列表。所以让我们为此创建一些视图模型
public class Course
{
public int ID { set;get;}
public string CourseName { set;get;}
public List<Student> Students { set;get;}
public Course()
{
Students=new List<Student>();
}
}
public class Student
{
public int ID { set;get;}
public string FirstName { set;get;}
}
现在在您的GET 操作方法中,创建我们视图模型的对象,初始化Students 集合并将其发送到我们的强类型视图。
public ActionResult StudentList()
{
Course courseVM=new Course();
courseVM.CourseName="Some course from your DB here";
//Hard coded for demo. You may replace this with DB data.
courseVM.Students.Add(new Student { ID=1, FirstName="Jon" });
courseVM.Students.Add(new Student { ID=2, FirstName="Scott" });
return View(courseVM);
}
现在在 Views/YourControllerName 下创建一个名为 EditorTemplates 的文件夹。然后在 Student.cshtml 下创建一个新视图,内容如下
@model Student
@{
Layout = null;
}
<tr>
<td>
@Html.HiddenFor(x => x.ID)
@Html.TextBoxFor(x => x.FirstName ) </td>
</tr>
现在在我们的主视图(StudentList.cshtml)中,使用EditorTemplate HTML helper 方法来带来这个视图。
@model Course
<h2>@Model.CourseName</h2>
@using(Html.BeginForm())
{
<table>
@Html.EditorFor(x=>x.Students)
</table>
<input type="submit" id="btnSave" />
}
这会将带有每个学生姓名的所有 UI 显示在包含在表格行中的文本框中。现在,当表单发布时,MVC 模型绑定将在我们的视图模型的Students 属性中包含所有文本框值。
[HttpPost]
public ActionResult StudentList(Course model)
{
//check for model.Students collection for each student name.
//Save and redirect. (PRG pattern)
}
Ajax化解决方案
如果您想对此进行 Ajaxify,您可以监听提交按钮的点击,获取表单并将其序列化并发送到相同的 post 操作方法。您可以返回一些指示操作状态的 JSON,而不是保存后重定向。
$(function(){
$("#btnSave").click(function(e){
e.preventDefault(); //prevent default form submit behaviour
$.post("@Url.Action("StudentList",YourcontrollerName")",
$(this).closest("form").serialize(),function(response){
//do something with the response from the action method
});
});
});