Hi,
How can I set the Html title from within a controllers action?
Hi,
How can I set the Html title from within a controllers action?
It sounds not very wise for controller to control the output. All a controller do, is to give viewdata to the output view and let the view determine what to do with it.
Please refer to the default ASP.net MVC template for how it is done.
I don't believe there is a way to simply set the title directly from the controller with out setting up your views to accept some sort of data associated with the information. Especially since to actually set the title you'll need to output data in between tags.
That said, I'm sure there's something you could do to make this easier on yourself. I'm more or less just thinking aloud here, so I can't guarantee this will work. If I was sure that I would set my title's on every action that I have, then I would keep the title tags in the master page and create a custom attribute so you could do something like this:
[CustomTitleAttribute(Title = "Hello World")]
public ActionResult Index()
{
return View();
}
It would be up to you to implement the attribute and set up how you capture this information in the view and/or master page.
Generally speaking, since you may want the title to change on pages that have dynamic data, the above is probably not something you should do. Instead, just incorporate some way to determine the title you need in a view model. Maybe even a base view model that subsequent view models can inherit from.
public class BaseViewModel
{
public string PageTitle { get; set; }
public string PageDescription { get; set; }
//etc.
}
Then in the views you can do this, or even in your master page I think:
<title><%= Model.PageTitle %></title>
I think from a standpoint of separating concerns(which is kinda the whole point) that would be the best way to go.