如何编辑一个IEnumerable 与ASP.NET MVC 3?
-
26-09-2019 - |
题
鉴于以下类型的
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映射值返回。
解决方案
您使用编辑器模板会做到这一点。这样的框架会照顾一切(从正确的命名输入字段正确绑定值后动作后)。
控制器:
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>
其他提示
IList
实现IEnumerable,所以你可以修改你的模型像这样:
public class SomeModel {
public string SomeProp1 { get; set; }
public string SomeProp2 { get; set; }
public IList<SomeValue> MyData { get; set; }
}
您可以使用IModelBinder
界面来创建特定型号的粘合剂。有几个方法可以做到这一点。您可以通过EditorFor
列表,并输出相应的IDS,什么不可以为模型创建将环的SomeValue
CSHTML。然后,在你ModelBinder
实现你会然后通过你的IDS阅读并绑定他们适当。我可以在一段时间后工作示例。
不隶属于 StackOverflow