2
votes

I have a viewmodel and it has a nested class what is not in connection other model class. I can fill the necessary data in this nested class (ClassX) to show those in the view but I can't get out data from the nested class (through MyViewModel) in the post action just when I give it in post action as another parameter. It appears in original viewmodel (MyViewModel) but its attributes are null/0.

public class MyViewModel
{
   public MyViewModel()
   {
      classX = new ClassX();
   }

   public ClassX classX;
   public int attrA {get;set;}
   ...
}
public class ClassX {}

//
// POST: /MyModel/Create
public ActionResult Create(MyViewModel myvm, **ClassX cx**, FormCollection collection)
{}

My question: Can I read data out from the nested class through the viewmodel class?

2
Just a guess - I think the conversion process will only bring over properties. I think you need to change "public ClassX classX;" to "public ClassX classX { get; set; }"Justin Beckwith
Thank you. I tried your suggestion and it worked.sada

2 Answers

0
votes

http://goneale.com/2009/07/27/updating-multiple-child-objects-and-or-collections-in-asp-net-mvc-views/ this is a good article for you

  MyViewModel myViewModel= new MyViewModel();
  UpdateModel(myViewModel, "MyViewModel");
  myViewModel.myViewModel= new myViewModel();
  UpdateModel(myViewModel.classX, "User.classX");
0
votes

If I understood your question correctly, you need BindAttribute.Prefix on your ClassX cx parameter of action method. This way, model binder will correctly bind values for it. The value for Bind.Prefix should be name of ClassX property in MyViewModel, in your example, the string - "classX"

//
// POST: /MyModel/Create
public ActionResult Create(MyViewModel myvm, [Bind(Prefix = "classX")]ClassX cx, FormCollection collection)
{}

Idea is in the following - on client side, when you submit the form, its values are sent to server like this

attrA=someValue
classX.SomeProperty=someValue
classX.SomeOtherProperty=someOtherValue

When passed to action parameters, this name=value string pairs are translated to objects. Names from left side of equality match to property names of MyViewModel, and the ClassX parameter stays empty. But then you specify Prefix = "classX", model binder matches strings after dot in left side of equality to ClassX property names, so that should fill values of ClassX too.