0

如果我有以下剃须刀页面:( 请原谅可怕的例子......)

Page1.cshtml

Hello @Model.Name, welcome to {sitename}

Page2.cshtml

{sitename} has had @Model.visitorcount today

在运行时,我想{sitename}用“Contoso”(这个 var 来自设置类)以及其他标签替换

我可以将 jQuery 与以下内容一起使用:

"$(body).replace("{sitename}", "Contoso")

这可能发生在_layoutorViewStart文件中以减少脚本,但我不喜欢这种方法。似乎它可能会导致大量代码混乱并且“看起来不对”

这里有更好的方法吗?也许使用控制器基类并以某种方式解析每个视图?

4

2 回答 2

2

Use the ViewBag in conjunction with a global filter.

E.g.

Page1.cshtml

Hello @Model.Name, welcome to @ViewBag.SiteName

Page2.cshtml

@ViewBag.SiteName has had @Model.visitorcount today

SiteNameIntoViewBagAttribute.cs

public class SiteNameIntoViewBagAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.Controller.ViewBag.SiteName = GetSiteTitle();
    }
}

Then register it in global.asax

public partial class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        //Blah blah blah

        GlobalFilters.Filters.Add(new SiteNameIntoViewBagAttribute ());

        //Blah blah blah
    }
}
于 2013-05-14T21:01:33.190 回答
0

正常的方法是添加您的 ViewModel 或 ViewBag 的站点名称 - 这基本上就是它们的用途。我相信任何其他解决方案最终都会将逻辑放入真正属于控制器的视图中。

于 2013-05-14T21:04:01.987 回答