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

ViewBag をグローバル フィルターと組み合わせて使用​​します。

例えば

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();
    }
}

次に、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 に答える