asp.net-mvc – 如何使用ASP.NET MVC 3编辑IEnumerable?

给出以下类型
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>

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...