在ASP.NET MVC中编辑列表时如何保留输入ID?

时间:2012-10-16 07:14:30

标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我正在使用ASP.NET MVC 4,但我认为这对于这个问题并不重要。

我的编辑视图有一个相对复杂的模型。像这样:

public class Recipe_model
{
    public string Name { get; set; }

    public List<Recipe_Ingredient_model> Ingredients { get; set; }
}

其中的成分是

public class Recipe_Ingredient_model
{
    public int RecipeID { get; set; }

    public int? UnitID { get; set; }

    public double? Quantity { get; set; }

    public Ingredient_model Ingredient { get; set; }
}

本身包含成分模型。

当我为此创建表单时,内置的Html.EditorFor()对于Recipe_model的属性之外的任何内容都不起作用,因此我使用部分视图来显示每个的编辑器子模型。

从接口到目前为止工作正常,但是当我将表单提交给控制器并尝试使用

自动绑定到Recipe_model
    [HttpPost]
    public ActionResult Edit(Recipe_model model)
    {
        return View(model);
    }

它失败了,因为部分视图中输入元素的id不符合正确的模式(我认为是ParentModel_Property)。

在部分视图中对ID进行硬编码或从控制器中的FormCollection手动绑定时,有一些方法可以获得在局部视图中生成的正确ID,以便模型自动绑定提交?

2 个答案:

答案 0 :(得分:0)

这是常见问题。使用EditorTemplates(模型的特殊文件夹)而不是简单的部分,绑定将自动运行。

例如,请查看此问题:Updating multiple items within same view

答案 1 :(得分:0)

除了@WebDeveloper给出的答案 您也可以尝试创建一个自定义模型绑定器,虽然稍微复杂一些但是会增加在长期运行中将表单值发布和绑定到对象的简易性 看看这里http://patrickdesjardins.com/blog/asp-net-mvc-model-binding

您必须手动获取所有表单值并将它们绑定到model一次,然后您就可以使用剃刀上的@HtmlFrom方法执行任何操作,您将获得所有内容的价值action methods中的对象,如你所愿。