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

3
  • 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
    – user3559349
    Feb 15, 2018 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 for example in mvc (may need to be modified for core-mvc)
    – user3559349
    Feb 15, 2018 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, 2018 at 17:48

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.