dan*_*n27 9 c# asp.net-mvc asp.net-mvc-4
我可以找到MVC4应用程序的每个示例都有一次编辑处理一行数据.它显示所有数据行,每行都有一个编辑,可以将您带到另一个页面,并允许您编辑该行.
我想要做的是在行中显示所有数据元素,而不是让用户必须在每一行上单击EDIT,所有行的数据点都已经在用户可以直接更新的文本框中.并且页面上只有一个SAVE可以立即保存所有更新/编辑.
如何设置我的MVC应用程序来支持它?
Shy*_*yju 12
您可以使用EditorTemplates.以下示例显示了正常的表单发布示例.如果需要,可以使用该serialize
方法并发送表单值来对其进行解析.
假设您需要编辑课程的学生姓名列表.所以让我们为此创建一些视图模型
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;}
}
Run Code Online (Sandbox Code Playgroud)
现在,在您的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);
}
Run Code Online (Sandbox Code Playgroud)
现在在Views/YourControllerName下创建一个名为EditorTemplates的文件夹.然后在调用下面的内容下创建一个新视图Student.cshtml
@model Student
@{
Layout = null;
}
<tr>
<td>
@Html.HiddenFor(x => x.ID)
@Html.TextBoxFor(x => x.FirstName ) </td>
</tr>
Run Code Online (Sandbox Code Playgroud)
现在在我们的主视图(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" />
}
Run Code Online (Sandbox Code Playgroud)
这将使您的每个学生姓名的所有UI都包含在表格行中的文本框中.现在,当发布表单时,MVC模型绑定将在Students
我们的viewmodel 的属性中具有所有文本框值.
[HttpPost]
public ActionResult StudentList(Course model)
{
//check for model.Students collection for each student name.
//Save and redirect. (PRG pattern)
}
Run Code Online (Sandbox Code Playgroud)
Ajax化解决方案
如果你想要Ajaxify这个,你可以听取提交按钮点击,获取表单并序列化它并发送到相同的post action方法.您可以返回一些指示操作状态的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
});
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9735 次 |
最近记录: |