问题
I'm working on a ASP.NET MVC 3 application, but I'm rather new to MVC in general.
I have a partial view in a my application layout view that needs to have data passed to it. this will appear on every page. Is there a way to make this happen so I don't have to load that data into the view model for every action in the entire site?
As in, if a user navigates to Mysite/admin/settings, I would like to have the partial view on the layout be able to somehow receive the data that it needs without me needing to put that code in the Settings action in the Admin controller.
On this same note, how do you pass data to the layout view of an application anyway?
回答1:
In these situations I usually use a base ViewModel for my Views
public class ApplicationViewModel
{
public string UserName {get; set;}
....
}
public class SettingsViewModel : ApplicationViewModel
{
}
all your views would inherit from that ViewModel. Your layout would expect it as well
_layout.cshtml:
@model ApplicationViewModel
....
<h1>hello @Model.UserName</h1>
hopefully this answers your question
回答2:
Partial only renders a view. You need to provide the model manually.
You can create an action for the view you want and render it with Html.Action( actionName ).
Make an action for example menu
which will create a model that will be provided to the menu
view.
Now you can call the @Html.Action("menu")
from wherever, and it will be rendered autonomously. (you can ofcourse provide a controller name as well, and even custom routeData)
You might also want to set Layout = null;
in the view to avoid using the master layout of the whole site.
回答3:
This is how I pass a value to the partial view from my layout page:
Layout page code:
Html.RenderPartial("_SubMenuLeft", new ViewDataDictionary { {"category", "MMG"} });
and in my _SubMenuLeft.cshtml
(partial view)
@if (ViewData["category"] == "MMG")
{
...
}
Hope it helps someone for future reference.
来源:https://stackoverflow.com/questions/8525658/asp-net-mvc-3-pass-data-to-a-partial-view-in-layout