pass an object to a user controls ViewModel in asp.net mvc
I h开发者_StackOverflow中文版ave a View that uses a specific ViewModel.
The viewModel has various object e.g. Foo, Bar...etc
I have a user control that has its own ViewModel which contains a Foo object.
How do pass the Foo object from the page View to the usercontrols ViewModel?
If you do this:
<% Html.RenderPartial("partial", Model.Foo); %>
Then one of two things will happen.
- If the View's
Model.Foo
is non-null, then the UserControl'sModel
will be equal to the View'sModel.Foo
, and the UserControl'sModel.Foo
will be the View'sModel.Foo.Foo
. - *If the View's
Model.Foo
is null, then the UserControl'sModel
will be equal to the View'sModel
, and the UserControl'sModel.Foo
will be the View'sModel.Foo
. If the View'sModel
andModel.Foo
are not the same type and the View'sModel
is non-null and if the UserControl uses strongly typed view data, then you will get a runtime error since the UserControl's model is now of typeTViewModel
instead ofTUserControlModel
.
Are you looking for this:
<% Html.RenderPartial("partial", Model.Foo); %>
精彩评论