展现在MVC3布局文件帐户信息的最佳方式帐户、布局、方式、文件

2023-09-04 04:32:54 作者:奈何桥上等你

我使用MVC3,并有一个布局文件,它是适用于所有的我的意见。在布局文件,我想显示关于当前登录的用户的一些信息。

I am using MVC3, and have a Layout file that is common for all of my Views. In the layout file, I would like to show some information regarding the currently logged in user.

我现在的工作,但只有这样我发现了如何是设置在操作方法的一些ViewBag领域,并挑选他们在布局文件。这意味着我将不得不在中ViewBag领域从我的一切行动的方法,或者至少使该设置它们的方法,并呼吁所有我的行动方法这个方法。

I got it working now, but the only way I found out how to is to set some ViewBag fields in the actions methods, and pick them up in the layout file. This means that I will have to the the ViewBag fields from all my action methods, or at least make a method that sets them, and call this method from all my action methods.

有没有中央的方式来完成这件事?绝对最好是做一次,在一个地方布局文件,但是如果每个控制器有没有其他选择一个地方可能不够好。

Are there any central way to get this done? The absolute best is to do it once for the layout file in one place, but if no other option one place per controller might be good enough.

推荐答案

正确的方法是调用 Html.RenderAction()布局文件中,您希望那里的用户特定的细节。然后创建一个合适的操作方法某处读取用户的账户信息,并将其返回作为视图(局部视图)或原始的HTML(返回内容(...) )。

The right way is to call Html.RenderAction() inside the layout file, where you want the user-specific details. Then create a suitable Action method somewhere which reads the user's account details and returns them as a view (partial view) or as raw html (return Content("...")).

这样的话,你还可以使用缓存的页面布局,保持用户的帐户信息区域未缓存的(因为它是为每一位用户明显不同)的能力。

That way, you can also benefit the ability to cache the layout page and keep the user's account details region uncached (since it's obviously different for every user).

设置ViewBag是不是一个好主意,它不是强类型,它打破了MVC的正确的模式。

Setting a ViewBag is not a good idea, it's not strongly type and it breaks the correct schema of MVC.