asp.netasp.net-mvcasp.net-mvc-4

How to set the page title and meta info in a view in ASP.NET MVC


I am very new to MVC and I am converting an ASP.NET WebForms application to ASP.NET MVC. I have a shared layout (equivalent to the master page in ASP.NET WebForms), I would like to set the meta and title information per view but I see no options for this.


Solution

  • Typically, in your layout, you'll have something like this:

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>@ViewBag.Title</title>
         <!-- the rest omitted for brevity -->
    

    The important part is @ViewBag.Title. This bit of razor syntax encodes and writes the value of ViewBag.Title. ViewBag is a property on all razor views to a dynamic type that uses the ViewData dictionary as its backing store. ViewData is just a dictionary where you can store random stuff that you want to use in your view.

    In your controller, layout, or view, you can get or set ViewBag.Title. Here's an example of how to set it in a view that uses your layout (called _Layout.cshtml in this example):

    @{
       ViewBag.Title = "My View's Title";
       Layout = "~/Views/Shared/_Layout.cshtml";
    }
    

    You can access the model metadata from ViewData.ModelMetadata. In this example, I enumerate the properties of the model and display the names:

    <ul>
    @foreach (var property in ViewData.ModelMetadata.Properties)
    {
      <li>@property.PropertyName</li>
    }
    </ul>