Alternative to ViewBag.Title in ASP.NET MVC 3

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

    ViewBag for title is perfectly fine (I'd even say it is the purpose of having ViewBag) - dynamic is not the absolute evil. "Title" is well known, unlikely to change and even predefined in view templates. I personally use following title:

    @(ViewBag.Title == null ? string.Empty : ViewBag.Title + " | ")Site Name
    

    If you are worried about mistyping ViewBag.Title you can make it strong type by creating custom WebViewPage but you will still have to use ViewBag or maybe HttpContext.Items inside that strongly typed property because there are multiple instances of WebViewPage created during rendering IIRC.

    I'd recommend to stick with ViewBag, creating own WebViewPage because of this seems like overkill - even creating single property on it if you already have custom WebViewPage is in my opinion just worthless complication - and that comes from person that is often overengineering things.

提交回复
热议问题