これにはエディタテンプレートを使用できます。以下の例は、通常の書式転記の例を示しています。 serialize
メソッドを使用してフォーム値を送信することで、必要に応じて自由に調整できます。
コースの学生名簿を編集する必要があると仮定します。それでは、今すぐあなたのGET
アクションメソッドでは、あなたが私たちのビューモデルのオブジェクトを作成し、Students
コレクションを初期化し、私たちの強く型付けされたビューに送ること
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;}
}
のためのいくつかのviewmodelsを作成してみましょう。
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);
}
は今EditorTemplates下のビュー/ YourControllerNameというフォルダを作成します。そして、その下に新しいビューを作成するには、このビューをもたらすために使用EditorTemplate HTMLヘルパーメソッド、コンテンツ以下
私たちのメインビュー(StudentList.cshtml)で今
@model Student
@{
Layout = null;
}
<tr>
<td>
@Html.HiddenFor(x => x.ID)
@Html.TextBoxFor(x => x.FirstName) </td>
</tr>
でStudent.cshtml
と呼ばれます。
@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)
}
Ajaxifiedソリューション
あなたがこれをAjaxifyしたい場合は、ボタンのクリックを提出するフォームを取得し、それをシリアル化し、同じポストアクションメソッドに送るために聞くことができます。保存後にリダイレクトする代わりに、操作のステータスを示す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
});
});
});
更新を送信するためのポストバックモデルまたはajaxモデルをお探しですか? – Heather
私はMVC4を勉強しているので、私は今、最も単純なものを探していると思います。それがポストバックであると仮定します。しかしどちらのモデルでも作業できます。ありがとう – dan27