MVC4 - Partial View Model binding during Submit

前端 未结 7 2231
野趣味
野趣味 2021-02-19 19:29

I have view model which has another child model to render the partial view (below).

public class ExamResultsFormViewModel
{
    public PreliminaryInformationView         


        
7条回答
  •  抹茶落季
    2021-02-19 20:04

    I know its a bit late but it might help to someone

    If you have complex model, you can still pass it into partial using:

    @Html.Partial("_YourPartialName", Model.Contact, new ViewDataDictionary()
    {
        TemplateInfo = new TemplateInfo()
        {
            HtmlFieldPrefix = "Contact"
        }
    })
    

    where I have defined model with property "Contact". Now what HtmlFieldPrefix do is add the property binding for each model "so the model binder can find the parent model"

    There is a blog post about it: http://www.cpodesign.com/blog/bind-partial-view-model-binding-during-submit/

    .NET Core 2 binding

    In .NET Core 2 and MVC the answer above will not work, the property is no longer settable.

    How ever the solution is very similar.

     @{ Html.ViewData.TemplateInfo.HtmlFieldPrefix = "Contact"; }
     @await Html.PartialAsync("_YourPartialName", Model.Contact)
    

    after you can submit your model, it will bind again.

    Hope that helps

提交回复
热议问题