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

标签 asp.net-mvc .net-4.0 ienumerable 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; }
}

我想为类型 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/

相关文章:

c# - 使用 TempData 在 Controller 操作之间传递细节是不好的做法吗?

c# - 更改 ASP.NET 标识消息

javascript - 制作带有链接的可点击 <div>,如何只触发一个 Action ?

WCF 4路由器服务配置问题

c# - 当我不在 for 循环中使用 ToList 方法时,为什么会失败?

javascript - 为什么一个 ko.mapping.fromJS 工作而另一个不工作?

c# - 在 .NET 4 中,BeginInvoke 和 Task 是否使用相同的线程池?

.NET 4.0 任务 : Rethrow Exception to UI Thread in Task. 继续

c# - 从 IEnumerable C# 返回列表<object>

c# - 用于公开列表成员的 IEnumerable vs IReadonlyCollection vs ReadonlyCollection