给出以下类型
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的通常文本字段,然后包含SomeModel.MyData集合中每个SomeValue的文本字段的表。
这怎么做?这些价值观如何回归到模型?
我目前有一个表单显示每个值的文本字段,但它们都具有相同的名称和相同的Id。这显然是无效的HTML,并将阻止MVC将值映射回来。
解决方法
您将使用编辑器模板来执行此操作。这样,框架将处理所有内容(从命名输入字段到在后期操作中正确绑定值)。
控制器:
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>