MVC3,从列表中获取更新的表单数据

问题描述:

我有一个强类型的视图,模型中有一个自定义对象列表。MVC3,从列表中获取更新的表单数据

在视图中显示我的文本框列表中的每个对象:

@using (Html.BeginForm("SaveData", "Localization", FormMethod.Post)) 
{ 
     foreach (YB.LocalizationGlobalText m in Model.GlobalTexts) 
    { 
      @Html.Label(m.LocalizationGlobal.Name) 
      @Html.TextBoxFor(model => m.Text) 
      <br /> 
    } 
    <input type="submit" value="Save" /> 
} 

现在我怎么才能从文本框更新的数据在我的模型。 我可以在看的FormCollection更新的数据有:

[HttpPost] 
    public virtual ActionResult SaveData(FormCollection form) 
    { 
     // Get movie to update 
     return View(); 
    } 

形式[“m.Text”] =“testnewdata1,testnewdata”

但我怎么得到这个映射到模型,所以我有每个对象的更新值。 或者我怎样才能得到它干净地从的FormCollection,这样的事情..形成[someid] [“m.Text”]

编辑:

我也试过路过模型作为参数,但模型数据为空。

[HttpPost] 
     public virtual ActionResult SaveData(LocalizationModel model, FormCollection form) 
     { 
      // Get movie to update 
      return View(); 
     } 

当我看着模型:model.GlobalTexts = NULL

[HttpPost] 
public virtual ActionResult SaveData(int movieId, FormCollection form) 
{ 
    // Get movie to update 
    Movie movie = db.Movies.Where(x => x.Id == movieId); 
    // Update movie object with values from form collection. 
    TryUpdateModel(movie, form); 
    // Do model validation 
    if (!ModelState.IsValid) 
     return View(); 
    return View("success"); 
} 

编辑看到这个问题,我问了一段时间后:How to use multiple form elements in ASP.NET MVC

可以说,你有这样的观点:

@model IEnumerable<CustomObject> 

@foreach (CustomObject customObject in Model) 
{ 
    <div> 
     @Html.TextBox(customObject.CustomProperty); 
     <!-- etc etc etc --> 
    </div> 
} 

重构这样的:

@model IEnumerable<CustomObject> 

    @for (int count = 0; count < Model.Count(); count++) 
    { 
     <div> 
      <!-- Add a place for the id to be stored. --> 
      @Html.HiddenFor(x => x[count].Id); 

      @Html.TextBoxFor(x => x[count].CustomProperty); 
      <!-- etc etc etc --> 
     </div> 
    } 
在动作方法

现在这样做:

public virtual ActionResult SaveData(IEnumerable<CustomObject>) 
{ 
    // You now have a list of custom objects with their IDs intact. 
} 

它比更容易如果你使用编辑器,但是我会让你自己弄清楚它们,因为它们非常简单。我连接的问题中接受的答案显示了一个例子。

注意:如果需要,您可以用IList替代IEnumerable。

+0

我该如何获得ID?我试图保存每一个对象,而不仅仅是一个。 – redrobot 2011-03-03 21:08:16

+0

我将通过编辑进行更新。钻孔。我忘了你正在处理一个对象列表。 – Chev 2011-03-03 21:09:23

+0

有你去,告诉我,如果这让你在正确的轨道上。 – Chev 2011-03-03 21:20:19

如果我正确理解你的问题,你可以简单地使用您的视图模型作为保存数据的参数,它会自动将其映射:

[HttpPost] 
public virtual ActionResult SaveData(ViewModelType viewmodel) 
{ 
    // Get movie to update 
    return View(); 
} 
+1

是的,我试过,但模型是空的。 – redrobot 2011-03-03 21:02:06