简体   繁体   中英

pass an object to a user controls ViewModel in asp.net mvc

I have a View that uses a specific ViewModel.

The viewModel has various object eg 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.

  1. If the View's Model.Foo is non -null , then the UserControl's Model will be equal to the View's Model.Foo , and the UserControl's Model.Foo will be the View's Model.Foo.Foo .
  2. *If the View's Model.Foo is null , then the UserControl's Model will be equal to the View's Model , and the UserControl's Model.Foo will be the View's Model.Foo . If the View's Model and Model.Foo are not the same type and the View's Model 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 type TViewModel instead of TUserControlModel .

您在寻找这个吗?

<% Html.RenderPartial("partial", Model.Foo); %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM