MVC4 - Partial View Model binding during Submit

前端 未结 7 2272
野趣味
野趣味 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:00

    I also ran into this problem. I will explain my solution using your code. I started with this:

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

    The action corresponding to the http post was looking for the parent model. The http post was submitting the form correctly but there was no reference in the child partial to the parent partial. The submitted values from the child partial were ignored and the corresponding child property remained null.

    I created an interface, IPreliminaryInfoCapable, which contained a definition for the child type, like so:

    public interface IPreliminaryInfoCapable
    {
        PreliminaryInformationViewModel PreliminaryInformation { get; set; }
    }
    

    I made my parent model implement this interface. My partial view then uses the interface at the top as the model:

    @model IPreliminaryInfoCapable
    

    Finally, my parent view can use the following code to pass itself to the child partial:

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

    Then the child partial can use the child object, like so:

    @model IPreliminaryInfoCapable
    ...
    @Html.LabelFor(m => m.PreliminaryInformation.ProviderName)
    etc.
    

    All of this properly fills the parent model upon http post to the corresponding action.

提交回复
热议问题