Alternative to ViewBag.Title in ASP.NET MVC 3

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

    There is nothing wrong with using ViewBag.Title = "My Title";

    All you are doing is use a dynamic property.

    The question is really where the information should be "declared".

    Ie, where is it most accessible for the purposes at hand.

    If it is on a per page basis, then that is the right place.

    If, however, the title of the page can be derived from the Model, then you should do that.

    In this case, I would probably use a base class for the ViewModel that you use, and create a PageTitle property there that contains the logic to derive the page title from properties in the Model.

    So:

    Model.PageTitle
    

    In summary, horses for courses and don't be afraid of using dynamic properties... so long as you understand what they are and what they do.

提交回复
热议问题