Home Sub viewmodel inside ViewModel returning null
Reply: 0

Sub viewmodel inside ViewModel returning null

Shwrk Published in 2018-01-12 12:00:11Z

I have 2 views; one for adding a user record, and another one for further processing based on some conditions. There are some sections which overlap between the two pages, some sections with minor changes and some sections which are entirely different.

My goal is to reuse viewModels where plausible. For the section with minor changes.. I have a viewModel called C (for common) which contains common props in both pages. I render C as a partial View. Then there are 2 viewModels A and B; in which C is a property and other extra fields become remaining properties.

My problem is that viewModel C is returning null.

In the view, each property of C is mapped to a field with name A.C.FieldName

The validations based on data annotations are triggering as well. but on form submit; the model C inside A is null. I am able to access all other field values


VM1 is the first viewModel. A,D,E are subViewModels. C is used inside A.

// ViewModel 1st view

    public class VM1  
        // each property denotes a section 

       public A objA { get; set; } 

       public D objD { get; set; }

       public E objE { get; set; }

   public class A()
     public C objC = new C(); // contains some common props in view 1 and 2

   ..... // other props specific to view 1

// View

   <form action="ActionName/ControllerName" method="post"> 

  @Html.Partial("EditorTemplates/_sectionC",Model.A.C, new ViewDataDictionary(ViewData)
                            TemplateInfo = new System.Web.Mvc.TemplateInfo
                                HtmlFieldPrefix = "A.C"
....other sections



   public ActionResult ActionName(VM1 viewModel)
  // viewModel.A.C is null here 

In the partial view rendered in view, the name attribute looks like A.C.FieldName and the client side data validation on regex, maxlength etc fire as well. Can't get it to bind in controller.


The problem, as Stephen Muecke pointed out was that I didn't declare the model C as a property in class A. Please refer When I post back to my controller all values for my model are null

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.308113 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO