0

I have a main view with a model AViewModel:

public class AViewModel
{
    public int P1 { get; set; }

    public BViewModel P2 { get; set; }
}

I have a partial view with BViewModel:

public class BViewModel
{
    public string P1 { get; set; }

    public string P2 { get; set; }
}

From the main view I render the partial view as the following.

await Html.RenderPartialAsync("~/Views/_B.cshtml", Model.P2);

On the main view, on submit ([HttpPost] Index controller method), I'm expecting the AViewModel.P2 to be populated with the BViewModel coming from the partial view, but it's not. What am I doing wrong? Is there a way to populate the original property (namely AViewModel.P2) with information collected from the partial view?

In other words, the problem is that on the controller method, model.P2.P1 and model.P2.P2 are null

yazanpro
  • 4,512
  • 6
  • 44
  • 66
  • 1
    Because your partial view is based on `BViewModel` therefore create `name` attributes which are `name="P1"` etc, but to bind to `AViewModel` they need to be `name="P2.P1"` etc –  Feb 15 '18 at 23:29
  • 1
    Use an `EditorTemplate` (or ViewComponents), not a partial, but if you really want to use a partial, you need to to specify the `HtmlFieldPrefix`. Refer [this answer](https://stackoverflow.com/questions/29808573/getting-the-values-from-a-nested-complex-object-that-is-passed-to-a-partial-view/29809907#29809907) for example in mvc (may need to be modified for core-mvc) –  Feb 15 '18 at 23:33
  • You first comment is the correct answer sir, while the second comment seems not to be supported in MVC Core since `Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary.TemplateInfo` is read only. – yazanpro Feb 16 '18 at 17:48

0 Answers0