Passing Data to Master Page in ASP.NET MVC

MVC 4 master page _Layout pass data

First, don't call it a master page. That's from Web Forms. In MVC, _Layout.cshtml is a "layout". That may seem like semantics, but it's important to differentiate because in Web Forms, the master page is a true page in it's own right, with it's own code behind. In MVC, a layout is only an HTML template with some placeholders. The controller, and specifically the action of the controller that was requested, is solely responsible for the page context. That also means you can't have a _Layout action that adds context to the layout because that action is not being called, and even if you did (by going to a URL like /Shared/_Layout in your browser, it would fail when loading _Layout.cshtml as a view, because it needs a superficial view to fill in the call to @RenderBody().

If you want to render something with its own context in your layout, then you must use child actions:

Controller

[ChildActionOnly]
public ActionResult Something()
{
// retrieve a model, either by instantiating a class, querying a database, etc.
return PartialView(model);
}

Something.cshtml

@model Namespace.To.ModelClass

<!-- HTML that utilizes data from the model -->

_Layout.cshtml

@Html.Action("Something", "ControllerSomethingActionIsIn")

Passing data to Master Page in ASP.NET MVC

If you prefer your views to have strongly typed view data classes this might work for you. Other solutions are probably more correct but this is a nice balance between design and practicality IMHO.

The master page takes a strongly typed view data class containing only information relevant to it:

public class MasterViewData
{
public ICollection<string> Navigation { get; set; }
}

Each view using that master page takes a strongly typed view data class containing its information and deriving from the master pages view data:

public class IndexViewData : MasterViewData
{
public string Name { get; set; }
public float Price { get; set; }
}

Since I don't want individual controllers to know anything about putting together the master pages data I encapsulate that logic into a factory which is passed to each controller:

public interface IViewDataFactory
{
T Create<T>()
where T : MasterViewData, new()
}

public class ProductController : Controller
{
public ProductController(IViewDataFactory viewDataFactory)
...

public ActionResult Index()
{
var viewData = viewDataFactory.Create<ProductViewData>();

viewData.Name = "My product";
viewData.Price = 9.95;

return View("Index", viewData);
}
}

Inheritance matches the master to view relationship well but when it comes to rendering partials / user controls I will compose their view data into the pages view data, e.g.

public class IndexViewData : MasterViewData
{
public string Name { get; set; }
public float Price { get; set; }
public SubViewData SubViewData { get; set; }
}

<% Html.RenderPartial("Sub", Model.SubViewData); %>

This is example code only and is not intended to compile as is. Designed for ASP.Net MVC 1.0.

ASP.NET: Passing data from content page to master page

On your master page create a public property - something along the lines of:

public string LabelValue
{
get{ return this.headerLabel.Text;}
set{ this.headerLabel.Text = value;}
}

Then, on your child page you can do this:

((MyMasterPage)this.Master).LabelValue = "SomeValue";

Pass data to Master Page with ASP.NET MVC

Put your strings into the ViewData collection,

ViewData["MenuString1"] = "My First String";
ViewData["MenuString2"] = "My Second String";

and retrieve them in the Master Page like this:

myMenu.Property1 = ViewData["MenuString1"].ToString();
myMenu.Property2 = ViewData["MenuString2"].ToString();

http://nerddinnerbook.s3.amazonaws.com/Part6.htm

How to pass viewmodel to a layout/master page?

It's an interesting debate topic -> passing view models to the master page / layout vs ViewBags.

I'm -hate- using ViewBags so I have view models for all my view-layers. Starting with the _layout.cshtml and upwards. Any view that uses a Layout .. well .. that view model just inherits the Layout .. or whatever view is below it .. and this is repeated until you hit the bottom level which is usually the _layout...

My RavenOverflow project has some sample code that shows this.

  • This is the the layout view, defined.
  • Here is the layout view model, defined.
  • This is the view that uses a layout.
  • Here is the view model, for that previous view.
  • This is some controller code, that creates the model .. which is then passed into the View.

How to pass value from masterpage to contentpage ASP.Net C#

One way is to use the master parameter on Page and read anything public from master page. Here's an example

Master Page

public partial class cMasterPage : System.Web.UI.MasterPage
{
public string getUserName
{
get
{
return "what ever";
}
}

protected void Page_Load(object sender, EventArgs e)
{

}
}

Page

public partial class cPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cGetValue = ((cMasterPage)Master).getUserName;
}
}

Passing data from controller to master page - based on currently logged in user

You could use child actions along with the Html.Action and Html.RenderAction helpers. So you could have a controller action which returns a view model indicating the currently logged in user info:

public MenuController: Controller
{
public ActionResult Index()
{
// populate a view model based on the currently logged in user
// User.Identity.Name
MenuViewModel model = ...
return View(model);
}
}

and have a corresponding strongly typed partial view which will render or not the menus. And finally inside the master page include the menus:

<%= Html.Action("Index", "Menu") %>

This way you could have a completely separate view model, repository and controller for the menu. You could still use constructor injection for this controller and everything stays strongly typed. Of course there will be a completely different view model for the main controller based on the current page. You don't need to have base controllers or some base view model that all your action should return.



Related Topics



Leave a reply



Submit