MVC4 - Partial View Model binding during Submit

Viewed 26891

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

public class ExamResultsFormViewModel
{
    public PreliminaryInformationViewModel PreliminaryInformation { get; set; }

    public string MemberID { get; set; }

    public string MemberName { get; set; }

    public int PatientID { get; set; }

    public string ConfirmationID { get; set; }

    public bool IsEditable { get; set; }

    #region Select Lists
    public SelectList ProviderOptions { get; set; }
    #endregion
}

public class PreliminaryInformationViewModel
{
    public string ProviderName { get; set; }

    public string ProviderID { get; set; }

    public string ServiceLocation { get; set; }
}

This PreliminaryInformationViewModel view model also used as a child models in another view model since this preliminary information can be updated at different pages.

So I created this preliminary information as a separate partial and to include in other pages.

@{Html.RenderPartial("_PreliminaryInformation", Model.PreliminaryInformation);}

Inside the partial

@model Web.Models.Preliminary.PreliminaryInformationViewModel
<div>
    @Html.TextBoxFor(x => x.DateOfService })
</div>

But the problem is during submit this preliminary model is always null due to the reason HTML name attribute is always is rendered as

but when I pass the parent model to the partial as below.

@model Web.Models.Exam.ExamResultsFormViewModel
<div>
    @Html.TextBoxFor(x => x.PreliminaryInformation.DateOfService })
</div>

Now the HTML element is generated as

<input type = 'text' name='PreliminaryInformation.DateOfService.DateOfService' id='PreliminaryInformation.DateOfService'>

and it binds properly during the submit.

I understand MVC bind the element value based on the name attribute value, but the second implementation would need me to create a multiple partial for each page, which I don't like.

So far I couldn't find a solution to work with the first implementation, is there way I can make preliminary information model value bind during submit with the first implementation.

7 Answers

You can add the HtmlFieldPrefix to the top of your partial view:

@{
    ViewData.TemplateInfo.HtmlFieldPrefix = "Contact";
}

This is the same approach as that described by @cpoDesign but it means you can keep the prefix in your partial view if you need to do that.

For .net core 2 and mvc, use do like below:

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