Alternative to ViewBag.Title in ASP.NET MVC 3

前端 未结 8 1849
不思量自难忘°
不思量自难忘° 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 .Models.Base.EveryPageViewModel
    

    In _Layout.shtml ...

    @Model.Title
    

    In your Model ...

    /// 
    /// Index View Model
    /// 
    public class IndexViewViewModel : EveryPageViewModel {
    
    }
    

    In EveryPageViewModel

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

    In your controller action

        /// 
        /// Index
        /// 
        /// 
        public ActionResult Index() {
            var model = new IndexViewViewModel();
            model.Title = "Home";
            return View(model);
        }
    

提交回复
热议问题