Complex models and partial views - model binding issue in ASP.NET MVC 3

后端 未结 2 1064
耶瑟儿~
耶瑟儿~ 2020-11-28 22:39

I have 2 models in my sample MVC 3 application, SimpleModel and ComplexModel, shown below:

public class SimpleModel
{
    public st         


        
相关标签:
2条回答
  • 2020-11-28 22:54

    Instead of:

    @Html.Partial("_SimplePartial", Model.Simple)
    

    I would recommend you using Editor templates:

    @model ComplexModel
    @using (Html.BeginForm()) 
    {
        @Html.EditorFor(x => x.Simple)
        <input type="submit" value="Save" />
    }
    

    and then put the simple partial inside ~/Views/Shared/EditorTemplates/SimpleModel.cshtml or inside ~/Views/Home/EditorTemplates/SimpleModel.cshtml where Home is the name of your controller:

    @model SimpleModel
    @Html.LabelFor(model => model.Status)
    @Html.EditorFor(model => model.Status)
    

    Of course if you prefer to have the partial in some special location and not follow the conventions (why would you?) you could specify the location:

    @Html.EditorFor(x => x.Simple, "~/Views/SomeUnexpectedLocation/_SimplePartial.cshtml")
    

    then everything will come into place as expected.

    0 讨论(0)
  • 2020-11-28 23:00

    As Daniel Hall suggests in his blog, pass a ViewDataDictionary with a TemplateInfo where HtmlFieldPrefix is set to the name of the SimpleModel-property:

     @Html.Partial("_SimplePartial", Model.Simple, new ViewDataDictionary(ViewData)
        {
            TemplateInfo = new System.Web.Mvc.TemplateInfo
            {
                HtmlFieldPrefix = "Simple"
            }
        })
    
    0 讨论(0)
提交回复
热议问题