Say I pass data to a partial view like this
@Html.Partial("_LandingPage_CaseStudiesList", new { TrackAction = "Case Study Click", CaseStudies = Model.CaseStudies })
How do I then get the data in the partial?
I have tried Model["TrackAction"]
and Model.TrackAction
but neither work and I don't know what else to try.
If I debug into the code I can see the properties but just don't know what to use to get them back
Here is my partial
<ul id="case-studies-list" class="table">
@{
int counter = 1;
foreach (Asset caseStudy in caseStudies)
{
<li class="@(counter == 1 ? "first " : string.Empty)cell">
<a href="@caseStudy.Url" class="track-event" data-action="@trackAction" data-label="Case Study Download" data-value="@caseStudy.Name" target="_blank">
<span class="sprite @string.Format("case-study{0}", counter)"></span>
<span class="text">
@Html.Raw(caseStudy.Name)<br />
<span class="font11">@Html.Raw(caseStudy.Location)</span>
</span>
</a>
</li>
counter++;
}
}
</ul>
This is an image of what I get when I debug: http://i.imgur.com/OiReWZv.gif
When defining your partial view you define what class it will be using as its data context. i.e:
MVC requires that this be a concrete type. Because of this I would suggest creating a folder in your project called
ViewModels
and creating a class to hold your information. So given your example:Which you can then use when defining your partial view like so:
If you don't want to use a viewmodel then I would suggest looking into other methods like ViewBags.
You can pass an anonymous object as model to a partial view the way you have in your question:
Then you have a couple of options in your partial view:
Do not declare a model in your view (i.e. do not include a statement like
@model MyModel
at the top)Declare the model as dynamic (i.e. include a statement like
@model dynamic
)In both cases you should be able to access your properties as in
Also, you will not have intellisense on your view file and you will receive an exception at runtime if the property doesn't exist in the model.