0

I have an "Embedded Resource" view. In this view I am using the following model

public class TestModel
{
    public TestModel()
    {
        CustomModel1 = new CustomModel1 ();
        CustomModel2 = new CustomModel2();
    }

    public CustomModel1 CustomModel1 { get; set; }

    public CustomModel2 CustomModel2{ get; set; }
}

In this view I have a form and inside it I am using @Html.EditorFor instead of @Html.Partial, because when I use @Html.Partial the CustomModel1 passed to the action (when the form is submitted) is empty.

@Html.EditorFor(m => m.CustomModel1, Constants.CustomEmbeddedView1)

However when I use @Html.EditorFor and pass as a template a "Content" view

@Html.EditorFor(m => m.CustomModel1, "~/Views/Common/_CustomPartialView.cshtml")

I get the following error:

The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.Int32'.

If I set the "Content" view to be an "Embedded Resource" everything works fine.

Is there any way to resolve this problem? Perhaps there is another solution to the model binding problem instead of using @Html.EditorFor.

4

1 回答 1

1

我找到了解决我的问题的方法。我仍然不知道为什么会抛出错误,但至少我修复了模型绑定。

模型绑定的问题在于,当您调用@Html.Partial

@Html.Partial("~/Views/Common/_CustomPartialView.cshtml", Model.CustomModel1)

显示的元素(@Html.EditorFor(m => m.Name)例如,我在部分视图中使用)具有id="Name". 因此模型绑定尝试在 中查找“名称”属性TestModel,但名称属性在CustomModel1属性中。这就是模型绑定不起作用的原因,提交表单时 Name 属性为空字符串。

解决方法是设置 HtmlFieldPrefix。

var dataDictCustomModel1 = new ViewDataDictionary { TemplateInfo = { HtmlFieldPrefix = "CustomModel1" } };
@Html.Partial("~/Views/Common/_CustomPartialView.cshtml", Model.CustomModel1, dataDictCustomModel1 )

这样, Name 属性的 id 变为id="CustomModel1_Name",从而允许模型绑定器正确设置 Name 属性的值。

对此可能有更好的解决方案,但到目前为止,这是我想出的最好的解决方案。

于 2013-08-02T13:38:03.543 回答