Asp.net-Mvc
如何使用 ASP.NET MVC 3 編輯 IEnumerable<T>?
給定以下類型
public class SomeValue { public int Id { get; set; } public int Value { get; set; } } public class SomeModel { public string SomeProp1 { get; set; } public string SomeProp2 { get; set; } public IEnumerable<SomeValue> MyData { get; set; } }我想為
SomeModel包含常用文本欄位的類型創建一個編輯表單SomeProp1,SomeProp2然後為集合SomeValue中的每個欄位創建一個包含文本欄位的表格。SomeModel.MyData這是怎麼做到的?這些值如何綁定回模型?
我目前有一個顯示每個值的文本欄位的表單,但它們都具有相同的名稱和相同的 ID。這顯然不是有效的 HTML,並且會阻止 MVC 將值映射回來。
您可以使用編輯器模板來完成。這樣,框架將處理所有事情(從正確命名輸入欄位到正確地將值綁定回 post 操作)。
控制器:
public class HomeController : Controller { public ActionResult Index() { // In the GET action populate your model somehow // and render the form so that the user can edit it var model = new SomeModel { SomeProp1 = "prop1", SomeProp2 = "prop1", MyData = new[] { new SomeValue { Id = 1, Value = 123 }, new SomeValue { Id = 2, Value = 456 }, } }; return View(model); } [HttpPost] public ActionResult Index(SomeModel model) { // Here the model will be properly bound // with the values that the user modified // in the form so you could perform some action return View(model); } }查看 (
~/Views/Home/Index.aspx):<% using (Html.BeginForm()) { %> Prop1: <%= Html.TextBoxFor(x => x.SomeProp1) %><br/> Prop2: <%= Html.TextBoxFor(x => x.SomeProp2) %><br/> <%= Html.EditorFor(x => x.MyData) %><br/> <input type="submit" value="OK" /> <% } %>最後是編輯器模板(
~/Views/Home/EditorTemplates/SomeValue.ascx),它將為MyData集合的每個元素自動呼叫:<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyApp.Models.SomeValue>" %> <div> <%= Html.TextBoxFor(x => x.Id) %> <%= Html.TextBoxFor(x => x.Value) %> </div>