给定以下类型
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
收藏。这是怎么做到的?这些值如何绑定(bind)回模型?
我目前有一个显示每个值的文本字段的表单,但它们都具有相同的名称和相同的 ID。这显然不是有效的 HTML,并且会阻止 MVC 将值映射回来。
最佳答案
您可以使用编辑器模板来完成。这样,框架将处理所有事情(从正确命名输入字段到正确地将值绑定(bind)回 post 操作)。
Controller :
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>
关于asp.net-mvc - 如何使用 ASP.NET MVC 3 编辑 IEnumerable<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4233832/