ASP.NET MVC model binding – List of objects

Hướng dẫn dưới đây chỉ cách việc binding 1 list các đối tượng trong ASP.NET MVC

Ví dụ chúng ta có lớp Book với các thuộc tính như sau:

public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public DateTime DatePublished { get; set; }
}

Giao diện cho phép người dùng submit một danh sách các object lên Controller như hình sau

list

Mã nguồn của view Create.cshtml

@model List<BindingListObject.Models.Book>
@{
 ViewBag.Title = "Create";
}
<h2>Create</h2>
<p>
 @Html.ActionLink("Create New", "Create")
</p>
@using (Html.BeginForm("Create", "Book", FormMethod.Post))
{
 <table border="1" cellpadding="6">
 @for (int i = 0; i < Model.ToList().Count; i++)
 {
 <tr>
 <td>
 @Html.TextBox("books[" + @i + "].Title",Model[i].Title,new { @readonly = "readonly" })
 </td>
 <td>
 @Html.TextBox("books[" + @i + "].Author",Model[i].Author)
 </td>
 <td>
 @Html.TextBox("books[" + @i + "].DatePublished",Model[i].DatePublished)
 </td>

 </tr>
 }
 <tr>
 <td colspan="3">
 <input type="submit" value="Submit" />
 </td>
 </tr>
 </table>
}

BookController.cs với các action method để xử lý Create method

[HttpGet]
public ActionResult Create()
 {
 List<Book> books = new List<Book>();
 Book b1 = new Book();
 b1.Title = "C#";
 b1.Author = "Murach";
 b1.DatePublished = DateTime.Today;

 Book b2 = new Book();
 b2.Title = "ASP.NET with C#";
 b2.Author = "Murach";
 b2.DatePublished = DateTime.Today.AddDays(1);

 Book b3 = new Book();
 b3.Title = "ASP.NET with C# - part2";
 b3.Author = "Murach - 2";
 b3.DatePublished = DateTime.Today.AddDays(1);
 books.Add(b1);
 books.Add(b2);
 books.Add(b3);
 return View(books);
 }

 [HttpPost]
 public ActionResult Create(ICollection<Book> books)
 {
      //Your code here for HttpPost method 
      return View("BookInfor",books);
 }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s