Get variables in PartialView

2019-06-02 21:44发布

问题:

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

回答1:

You can pass an anonymous object as model to a partial view the way you have in your question:

@Html.Partial("_LandingPage_CaseStudiesList", new { TrackAction = "Case Study Click", CaseStudies = "fsdffd" })

Then you have a couple of options in your partial view:

  1. Do not declare a model in your view (i.e. do not include a statement like @model MyModel at the top)

  2. 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

@Model.TrackAction
@Model.CaseStudies 

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.



回答2:

When defining your partial view you define what class it will be using as its data context. i.e:

@model SomeViewModel

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:

public class MyViewModel
{
    public string TrackAction { get; set; }
    public string CaseStudies { get; set; }
}

Which you can then use when defining your partial view like so:

@Html.Partial("_LandingPage_CaseStudiesList", new MyViewModel{ TrackAction = "Case Study Click", CaseStudies = Model.CaseStudies })

If you don't want to use a viewmodel then I would suggest looking into other methods like ViewBags.