代码之家  ›  专栏  ›  技术社区  ›  Greg B

如何使用ASP.NET MVC 3编辑IEnumerable<t>

  •  17
  • Greg B  · 技术社区  · 14 年前

    给定以下类型

    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将值映射回。

    2 回复  |  直到 12 年前
        1
  •  14
  •   Darin Dimitrov    14 年前

    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>
    
        2
  •  1
  •   Buildstarted    14 年前

    IList

    public class SomeModel {
        public string SomeProp1 { get; set; }
        public string SomeProp2 { get; set; }
        public IList<SomeValue> MyData { get; set; }
    }
    

    IModelBinder EditorFor SomeValue ModelBinder