替代ViewBag.Title在ASP.NET MVC 3 [英] Alternative to ViewBag.Title in ASP.NET MVC 3
问题描述
默认情况下,ASP.NET MVC 3的新项目模板中添加以下为默认布局(以剃刀母版):
By default the new project template for ASP.NET MVC 3 adds the following to the default layout (masterpage in razor):
<title>@ViewBag.Title</title>
视图必须然后包含以下分配页面的标题,比如:
The view must then contain the following to assign the title of the page, for instance:
@{
ViewBag.Title = "Log On";
}
也许这只是我自己的preference但我发现使用ViewBag举行的称号有点不对(我想得太多了魔串味)。所以我的问题是:这种使用ASP.NET MVC 3剃须刀和(使用动态属性包),或者是你选择了更多的东西强类型的(可能涉及一个自定义的基类?)
Perhaps it is just my own preference but I find that using the ViewBag to hold the title a little bit wrong (I'm thinking too much magic-string flavor). So my question is: Is this the recommended best practice for people using ASP.NET MVC 3 and razor (using a dynamic property bag) or are you opting for something more strongly typed (perhaps involving a custom baseclass?)
推荐答案
我不认为这是坏的默认标题处理功能附带asp.net MVC3,其奥基做任何事情。
i dont think there is any thing bad with default title handling feature that ships with asp.net mvc3, its okie to do.
我个人是这样(写在下面)来处理的标题,我不是赞同低于code 或说其比默认功能更好的,它只是一个preference。
I personally do this(below written) to handle title, I am not endorsing the below code or saying that its better than default functionality, its just a preference.
主
<title>
@RenderSection("Title");
</title>
查看
@section Title
{
write title
}
有一件事我可以建议改善默认功能
@{
string pageTitle=@ViewBag.Title ?? "Title Not Set";
}
<title>@pageTitle</title>
所以每当你忘了将它添加在viewbag,页面上会显示标题= 标题没有设置
创建一个基类,然后让所有的控制器从基类继承也可以做。但我认为它需要这么多的痛苦,为标题
。
Creating a base class then making all your controllers inherit from that base-class can also be done. But i think its taking so much of pain for title
.
这篇关于替代ViewBag.Title在ASP.NET MVC 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!