开发者

Razor View Extension Method?

I want to create an extension method which I can use in CSHTML file using @this, so I can have accesss to Layout 开发者_StackOverflow社区and PageData properties in the method.

Now, what I want to know is which class to extend, I tried both StartPage and ViewStartPage.


You need to add the extension method to System.Web.Mvc.WebViewPage. ViewStartPage and StartPage represent the _ViewStart.cshtml file (and _PageStart.cshtml in ASP.NET WebPages) respectively.


Hallo,

If I understand it right a HTML helper method could help you.

You could pass as a parameter all variables you have in your page.

@Html.ShowMyText(Model.YourStringToUse)

And in your helper method you can do your logic and return something what should be rendered. (My be you can also modify some things in your helper.ViewContext object.

Your Html-helper could look like this:

public static HtmlString ShowMyText(this HtmlHelper helper,string pourStringToUse)
{ 
     CultureInfo cultureInfo = (CultureInfo)helper.ViewContext.HttpContext.Session["CurrentLanguage"];

    if (cultureInfo.IetfLanguageTag.Equals("en-EN") == true)
    {
        return new HtmlString("English");
    }
    else
    {
        return new HtmlString("Not English");
    }
}

So maybe it gives you a starting point. Anyway, it's possible that you don't have access to everything you need.


You should take the WebPageBase class, which all Razor views inherit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜