ASP.NET MVC 3 - pass data to a partial view in Layout

隐身守侯 提交于 2021-02-08 10:48:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!