Gre*_*g B 17 asp.net-mvc ienumerable .net-4.0 asp.net-mvc-3
鉴于以下类型
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; }
}
Run Code Online (Sandbox Code Playgroud)
我想创建该类型的编辑形式,SomeModel这将包含常规的文本字段SomeProp1,并SomeProp2再将装有一个文本字段,每个表SomeValue中SomeModel.MyData收集.
这是怎么做到的?如何将值绑定回模型?
我目前有一个表单显示每个值的文本字段,但它们都具有相同的名称和相同的ID.这显然不是有效的HTML,并且会阻止MVC将值映射回来.
Dar*_*rov 14
您可以使用编辑器模板来完成.这样,框架将处理所有事情(从正确命名输入字段到在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);
}
}
Run Code Online (Sandbox Code Playgroud)
查看(~/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" />
<% } %>
Run Code Online (Sandbox Code Playgroud)
最后是编辑器模板(~/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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6152 次 |
| 最近记录: |