Asp.net-Mvc

如何使用 ASP.NET MVC 3 編輯 IEnumerable<T>?

  • July 25, 2012

給定以下類型

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&lt;SomeValue&gt; MyData { get; set; }
}

我想為SomeModel包含常用文本欄位的類型創建一個編輯表單SomeProp1SomeProp2然後為集合SomeValue中的每個欄位創建一個包含文本欄位的表格。SomeModel.MyData

這是怎麼做到的?這些值如何綁定回模型?

我目前有一個顯示每個值的文本欄位的表單,但它們都具有相同的名稱和相同的 ID。這顯然不是有效的 HTML,並且會阻止 MVC 將值映射回來。

您可以使用編輯器模板來完成。這樣,框架將處理所有事情(從正確命名輸入欄位到正確地將值綁定回 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);
   }
}

查看 ( ~/Views/Home/Index.aspx):

&lt;% using (Html.BeginForm()) { &#37;&gt;

   Prop1: &lt;%= Html.TextBoxFor(x =&gt; x.SomeProp1) %&gt;&lt;br/&gt;
   Prop2: &lt;%= Html.TextBoxFor(x =&gt; x.SomeProp2) %&gt;&lt;br/&gt;
   &lt;%= Html.EditorFor(x =&gt; x.MyData) %&gt;&lt;br/&gt;
   &lt;input type="submit" value="OK" /&gt;
&lt;% } %&gt;

最後是編輯器模板(~/Views/Home/EditorTemplates/SomeValue.ascx),它將為MyData集合的每個元素自動呼叫:

&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl&lt;MyApp.Models.SomeValue&gt;" %&gt;
&lt;div&gt;
   &lt;%= Html.TextBoxFor(x =&gt; x.Id) %&gt;
   &lt;%= Html.TextBoxFor(x =&gt; x.Value) %&gt;
&lt;/div&gt;

引用自:https://stackoverflow.com/questions/4233832