0

Below is my view-model

public class ModelA
{
    public string name {get;set;}
    public string age {get;set;}
    public ModelB modelB {get;set;}
}

Here is partial view: _PartialView

@model ModelB
@*Bind all the into control*@
@Html.EditorFor(model => model.Name1)
@Html.EditorFor(model => model.Name2)
@Html.EditorFor(model => model.Name3)

Here is view

@model ModelA
using (Ajax.BeginForm("ActionName", "AreaName", new AjaxOptions()
{
     HttpMethod = "POST",
     InsertionMode = InsertionMode.Replace,
     OnSuccess = "BusinessPartner",
     OnFailure = "ErrorThrown"

}, new { name = "My App", id = "My App" }))
{
     @Html.EditorFor(model => model.name)
     @Html.EditorFor(model => model.age)
    @Html.Partial("_PartialView", Model.modelB)
     <input type="submit" class="btn btn-primary tabSubmit tab1" id="tab1Next" value="Save and Proceed" />
}

When I do a postback to the controller, I'm able to get the value in ModalA but ModalB is null. If I pass the whole Model instead of Model.modelB into the partial view, I'm able to get all the value. Is this a expected behavior for MVC? or do I need any configuration?

WenHao
  • 1,183
  • 1
  • 15
  • 46

1 Answers1

2

You need to replace

@Html.Partial("_PartialView", Model.modelB)

with

@Html.EditorFor(m => m.modelB)

and rename your partial to

/Views/Shared/EditorTemplates/ModelB.cshtml

so that its an EditorTemplate (note the name of the file must be the same as the name of the class). You can also locate it in /Views/yourControllerName/EditorTemplates folder)

Alternatively, you need to specify the HtmlFieldPrefix as per this answer

Note that if you inspect the html you partial is currently generating, it will include

<input name="Name1" ... />

whereas it needs to be

<input name="modelB.Name1" ... />

in order to bind to your model. Using an EditorTemplate rather than a partial will generate the correct name attributes

Community
  • 1
  • 1