Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting the page title, meta info in a view in asp.net mvc 4

I am very new to MVC and I am updating a web form application to mvc. I have a shared layout (masterpage in webforms), I would like to set the meta and title information per view but I see no options for this. thanks for any help.

like image 902
user516883 Avatar asked Sep 25 '12 15:09

user516883


3 Answers

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>
like image 130
moribvndvs Avatar answered Nov 14 '22 22:11

moribvndvs


In your method of controller.

ViewData["Title"] = "this is page one title";

in you view, have this. @ViewData["Title"])

if title is html, it should be @html.raw(ViewData["TopMessage"])

Razor engine is better for mvc, so I recommend you try razor when you create a new project. hope it help you.

like image 6
RED365 Avatar answered Nov 14 '22 21:11

RED365


I like to set page titles dynamically using the action and controller names. You can use a library like Humanizer to convert "SomeActionName" into "Some action name":

public static class HtmlHelperExtensions
{
    public static MvcHtmlString GetPageTitle(this HtmlHelper helper)
    {
        var actionName = helper.GetRouteDataValue("action");
        var controllerName = helper.GetRouteDataValue("controller");

        return new MvcHtmlString(controllerName.Humanize() + " - " + actionName.Humanize());
    }

    private static string GetRouteDataValue(this HtmlHelper helper, string value)
    {
        return helper.ViewContext.RouteData.Values[value].ToString();
    }
}

and then in your _Layout:

<title>@Html.GetPageTitle()</title>
like image 4
Craig Curtis Avatar answered Nov 14 '22 20:11

Craig Curtis