setting the page title, meta info in a view in asp.net mvc 4

前端 未结 4 1723
不知归路
不知归路 2021-02-12 15:04

I am very new to MVC and I am updating a web form application to mvc. I have a shared layout (masterpage in webforms), I would like to set the meta and title information per vie

4条回答
  •  孤街浪徒
    2021-02-12 15:45

    I like to set page titles dynamically using the action and controller names. You can use a library like Humanizer to convert "SomeActionName" into "Some action name":

    public static class HtmlHelperExtensions
    {
        public static MvcHtmlString GetPageTitle(this HtmlHelper helper)
        {
            var actionName = helper.GetRouteDataValue("action");
            var controllerName = helper.GetRouteDataValue("controller");
    
            return new MvcHtmlString(controllerName.Humanize() + " - " + actionName.Humanize());
        }
    
        private static string GetRouteDataValue(this HtmlHelper helper, string value)
        {
            return helper.ViewContext.RouteData.Values[value].ToString();
        }
    }
    

    and then in your _Layout:

    @Html.GetPageTitle()
    

提交回复
热议问题