Alternative to ViewBag.Title in ASP.NET MVC 3

前端 未结 8 1853
不思量自难忘°
不思量自难忘° 2021-02-05 05:20

By default the new project template for ASP.NET MVC 3 adds the following to the default layout (masterpage in razor):

@ViewBag.Title
<         


        
8条回答
  •  我在风中等你
    2021-02-05 05:22

    I like to create a PageTitle ActionFilter attributes rather than editing individual ViewBags

    Usage: keep the view the same

    @ViewBag.Title
    

    For controller-wide page title:

    [PageTitle("Manage Users")]
    public class UsersController : Controller {
        //actions here
    }
    

    For individual views:

    public class UsersController : Controller {
        [PageTitle("Edit Users")]
        public ActionResult Edit(int id) {
              //method here
        }
    }
    

    Attribute Code:

    public class PageTitleAttribute : ActionFilterAttribute
    {
        private readonly string _pageTitle;
        public PageTitleAttribute(string pageTitle)
        {
            _pageTitle = pageTitle;
        }
    
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            var result = filterContext.Result as ViewResult;
            if (result != null)
            {
                result.ViewBag.Title = _pageTitle;
            }
        }
    }
    

    Easy to manage and works like a charm.

提交回复
热议问题