0

I have 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?

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

i got it working by having Foo as a parameter in the constructor of the usercontrol view model. then passing the instance of the usercontrol viewmodel as the second parameter in the renderpartial method.
0

Are you looking for this:

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

1 Comment

is the user control clever enough to make its own Foo object equal to the one passed here? the View and the user control have different ViewModels which both contain a Foo

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.