Alternative to ViewBag.Title in ASP.NET MVC 3

前端 未结 8 1868
不思量自难忘°
不思量自难忘° 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:41

    I also do not use the ViewBag, at all.

    At the top of _Layout.shtml ...

    @model <YourWebAppNameSpace>.Models.Base.EveryPageViewModel
    

    In _Layout.shtml ...

    <title>@Model.Title</title>
    

    In your Model ...

    /// <summary>
    /// Index View Model
    /// </summary>
    public class IndexViewViewModel : EveryPageViewModel {
    
    }
    

    In EveryPageViewModel

    /// <summary>
    /// Every Page View Model
    /// </summary>
    public abstract class EveryPageViewModel {
        /// <summary>
        /// Title
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// Sub Title
        /// </summary>
        public string SubTitle { get; set; }
    }
    

    In your controller action

        /// <summary>
        /// Index
        /// </summary>
        /// <returns></returns>
        public ActionResult Index() {
            var model = new IndexViewViewModel();
            model.Title = "Home";
            return View(model);
        }
    
    0 讨论(0)
  • 2021-02-05 05:44

    we prefer strong title setting.. few sample from our BaseController class. (Page defines encapsulated view modal)

    protected override ViewResult View(string viewName, string masterName, object model)
    {
        if (model is Page)
        {
            ViewBag.Title = ((Page)model).Title;
            //HACK: SEO
            //TODO: SEO
        }
        return base.View(viewName, masterName, model);
    }
    
    0 讨论(0)
提交回复
热议问题