ASP.NET MVC 3-将数据传递到布局中的局部视图 [英] ASP.NET MVC 3 - pass data to a partial view in Layout

查看:40
本文介绍了ASP.NET MVC 3-将数据传递到布局中的局部视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发ASP.NET MVC 3应用程序,但对于MVC来说,我还是一个新手.

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?

例如,如果用户导航到Mysite/admin/settings,我希望布局的局部视图能够以某种方式接收所需的数据,而无需将代码放入设置"操作中.管理员控制器.

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?

推荐答案

在这种情况下,我通常将基本ViewModel用于视图

In these situations I usually use a base ViewModel for my Views

public class ApplicationViewModel
{
  public string UserName {get; set;}
  ....
}

public class SettingsViewModel : ApplicationViewModel
{
}

所有视图都将从该ViewModel继承.您的布局也会如此

all your views would inherit from that ViewModel. Your layout would expect it as well

_layout.cshtml:

_layout.cshtml:

@model ApplicationViewModel
....

<h1>hello @Model.UserName</h1>

希望这能回答您的问题

这篇关于ASP.NET MVC 3-将数据传递到布局中的局部视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆