ASP.NET MVC - Code Behind of Master Pages - asp.net

I am newbie for ASP.NET MVC 1.0. I am converting from a classic application built up with VS2008 .NET3.5. I created a master page, and the menu must be read from the database. Now the code that generate the HTML into the appropriate menu div in classic ASP.NET3.5 VS2008 was in the code behind of the master page.
I cannot understand now where the code beind of the master page is in ASP.NET MVC 1.0?
Anyone has examples?
Thanks

In MVC there are no longer Code-Behind classes. What you want is a Partial.
You'd use it like so:
<% Html.RenderPartial("MainMenu.ascx", ViewData["Menu"]); %>
If this Menu is going to be in all of your pages you can make your controllers subclass a custom controller class that always fills the Menu data first.
If messing with the MVC inheritance hierarchy is overkill you can also make a MenuController class and use the RenderAction in your view/master:
<% Html.RenderAction<MenuController>(x => x.MainMenu()); %>

You can still have code behind if you want. In your .master file put:
<%# Master Language="C#" AutoEventWireup="true"
Inherits="Site_Master" CodeFile="Site.Master.cs" %>
Then in your .master.cs:
public partial class Site_Master : ViewMasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}

Your master page is now a View, and Views should be passive. In other words, they shouldn't go look up things themselves.
It would be a much more correct approach (within the context of ASP.NET MVC) to pull the required data from the Model.
Take a look at this SO question for a related discussion.

There is a great tutorial on the ASP.NET site that shows how to do exactly this.
Briefly, you pass the data to the master page through the ViewData collection. To get the data into ViewData, create an application level controller. Have the page controllers inherit from the application controller instead of the base MVC controller.
Also, if you need to do things on your master page in reaction to the page being displayed, through this application controller you can tie into the ActionExecuting event. That will provide you information about the context of the page request currently being process.

Personally, I prefer using strongly typed views and ViewModels. If your master page requires data, then create a ViewModel for it. Ensure that every page's ViewModel inherits from this base ViewModel. Similarly, create a base controller that every other controller inherits from. Using Action Filters will allow you to ensure that the master ViewModel is populated implicitly. See this for an example.

Related

Call master page function from user control?

After searching Google I found one way to call a master page function from a user control:
Create an interface that includes your method.
Implement the interface in your master page
From your control, reference this.Page.Master via the interface type.
Call your method.
This is a good approach, but I don't know that can I call a master page static function in this way.
Another approach is :
// this is also good.
((MyMaster)this.Page.Master).MyFunction();
But I heard that this can also be done through an event.
1) Could someone show me how I could call a master page function from a user control through an event?
2) Also, how can I call a master page static function through a common interface way which I explained above.
I think it'd be better to have your user control raise an event and have your page listen for the event and then call the master page function. Controls shouldn't have any knowledge of the things that implement them - including whether or not the page has a master page.
In your content page, use the MasterType directive to generate the Master type. Then you can use the exposed Master property in the content page without casting. If you want to call a static function in the master from the content, you need to call it using the name of the master's code-behind class (since it is static)
content page:
<%# Page MasterPageFile="~/dir1/master1.master" ....... %>
<%# MasterType VirtualPath="~/dir1/master1.master" %> <!--This technique might change between .net versions. This is testing on 3.5-->
content page.cs
this.Master.nonStaticFunc();
dir1_master1.staticFunc();

A Base page in ASP.NET

Do you recommend from every web site created in Visual Studio, that you should create a Base page that serves as the parent class?
What are the exact benefits/drawbacks?
If you want to override the way something in ASP.NET works, it can be more efficient to build it into a base class rather than including the code in every page. Two specific instances where I've done this are:
IsPostback
Little-known fact: it's quite feasible to craft a request that, to ASP.NET, looks like a postback but is submitted with a GET request. Who does this? Hackers, that's who. A call to IsPostback in this case will return true, but it shoud really return false. To get round this, build a base class that overrides IsPostBack:
Public Class MyBase
Inherits System.Web.UI.Page
<DebuggerStepThrough()> _
Public Shadows Function IsPostback() As Boolean
'Check the built-in IsPostback and make sure this is a HTTP POST
Return (Page.IsPostBack AndAlso Request.HttpMethod.ToUpper = "POST")
End Function
End Class
Error Handling
In Beginning ASP.NET Security, Blowdart talks about the fact that if you use ASP.NET's error handling to redirect the client to a custom error page, hackers (again) can detect the redirection and flag it as an error that may be exploitable. A more secure pattern is to handle the Page's Error event and do a Server.Transfer (which doesn't send anything to the client). Again, doing this in a base class means you only write the code once:
public partial MyBase : System.Web.UI.Page
{
protected void Page_Error (object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
// Do something with the exception e.g. log it
...
Server.Transfer("~/mycustomerrorpage.aspx");
}
}
Yes, I do.
But please remember that the purpose of a base page is totally different from the purpose of a master page.
Let me explain.
Master pages
are layout elements used to share the same graphical features and part of the webforms behaviour (think a login/logout box with code-behind) across all pages that are associated to the master. Your final page classes will include a reference to the master page so the final result will appear as the master page including your page (check the source code to tell who contains whom)
Base pages
are (abstract? at least not sealed!) classes from which all your pages inherit from the code-behind view. Unless you explicitly and programmatically add controls to the basae page, ie. in the constructor via LoadControl method, all pages will look blank from the very beginning until you add code.
But often they are useful. If you want to override some of the base class methods, you can have the overriden behaviour shared across all pages. Or, you may want to expose application-specific objects to the children pages (a reference to a data access layer, a logger or whatever). An example is overriding UICulture property to retrieve the user-preferred language from cookies.
Both can be combined
Depending on your goals, you may combine master pages with base pages.
I suggest you to always create a base page class, since if your application's requirements change over time and you already created lots of pages, you can try to modify the base class to have the modifications propagated to all pages, according to the level of complexity of them.
Check out masterpages this is their primary purpose.
Here's a link: http://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx
This will serve as the template for your site. You would add a content section that would make up the body of your site. You can reference the master page is your subpages to have a consistent layout, menu, etc. for you site.
Also, like the others have noted. If you are running any commond code, just create a class a reference it from wherever you need it.
It depends on the size and complexity of your project. For small websites with minimal functionality, a base page might be overkill. That said, I would typically use it for site-wide functionality, such as security. I tend to keep functionality in the master pages to a minimum since their primary purpose is to organize your layout and factor out common display areas from you content pages to avoid duplication and ease maintenance.
To create a base page for use in a master page scenario, you could use the following syntax:
Master Page:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="MyProject.master.cs"
Inherits="MyProject.MasterPages.MyProject" %>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
Base Page:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPages/MyProject.Master"
AutoEventWireup="true" CodeBehind="BasePage.aspx.cs"
Inherits="MyProject.BasePage" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">
</asp:Content>
Content Page:
<%# Page Title="MyProject - Home" Language="C#"
MasterPageFile="~/MasterPages/MyProject.Master" AutoEventWireup="true"
CodeFileBaseClass="MyProject.BasePage" CodeFile="Default.aspx.cs"
Inherits="MyProject.Default"
Meta_Description="Code Snippet: Master Page and Base Page"
Meta_Keywords="master, base, content" Theme="Style" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">
</asp:Content>
If you need common functionality on all your pages that belongs to the page class, create a common base class.
If you don't need such common functionality on all your pages, don't create a common base class.
If you can't decide, having a base class isn't going to hurt anybody, so you might as well have one (I'd say you more often end up needing some common functionality than not)

Are ASP.net Content Web Forms able to access variables declared in the Code Behind section of it's Master Page?

I have a Master Page which controls the styling of my site. In the Code Behind, there are a few class instances instantiated as well as variables. These classes validate user access and then create user objects
I have a few Web Content Forms which carries out instructions based on the user objects. So far it seems that on each Web Content Form I have to create new instances of the classes found on the Master Page. This is doubling my work for every Web Content Form.
Is there anyway I can inhereit Classes and objects instantiated in the Master Page Code Behind?
Expose the objects (and even controls) as public properties (get only for controls) on the Master page. Then, in each aspx page you want access to these objects, add the following declaration at the top:
<%# MasterType VirtualPath="~/MyMasterPage.master" %>
As #Kristof points out, simply access your properties like Master.PropertyName
Also, you can determine if it makes sense to store the objects in the users Session (don't forget that they must be serializable if you use DB for session state). I do this often and control access to them via properties in a base Page class that all my pages inherit from. Actually, I have a base master, page, and usercontrol so I have access to the same properties (for me it's CurrentUser) everywhere.
I believe you can if you make the properties public.
Then in your child-page you can make the call something like this:
SiteMaster master = (SiteMaster)this.Master;
master.MyProperty = 0;
Where SiteMaster is the class for your master page. (SiteMaster is the default for the app templates)
Though my mind can deceive me, I haven't done it for a while...

How would this be done in ASP.NET MVC?

I've got some experience with ASP.NET MVC, but only with a web application where the content of the master page doesn't change. I've been wondering how you would handle a site where for example the menu (which is on the master page) is loaded from a database. Where would you load this data?
In WebForms, you would load the menu in the code-behind of the master page, or have the menu as a user control and do the loading in the code-behind of that. But where is this done in MVC?
Do you create a class that inherits from Controller that you use for all your Controllers and let that load the menu on every Action invocation (I don't know if that's possible, but it seems likely)?
Or do you create a utility method that you call in every Action where you want it (because some Actions may only return a partial view that won't reload the menu), which - while not disastrous - seems a little tiresome.
Or would you sin against MVC and just load it in the master page's code-behind?
What's the best approach to this (of course not limited to my solutions)?
ActionFilters are used to intercept a request and do some processing. You could use them.
Is it a sin against the MVC pattern?
You are breaking the MVC pattern to some extent. But the higher level point is: does it provide much more value if you force yourself not to break it? I don't think that puts you in much trouble, so keep simplicity and maintainability in mind and choose the way you'd do it in your specific situation.
I would create a model type that the master page gets its data from. Then derive the page's model type from the MasterModel.
The controller populates an instance of the PageModel, and the master page picks it up.
(Alternatively the master page's model could be an interface implemented by the pages' models.)
NB. In MVC CTPs doing this required some intermediate classes to override type matching to get to base class data. I don't know if this has been fixed in RTM.
The ASP.NET MVC Futures assembly (more info here) contains an extension method that lets you do this in your master page:
<% Html.RenderAction<NavigationController>(c => c.Show()); %>
You need to reference the assembly and add the "Microsoft.Web.Mvc" namespace in your web.config file for this to work.

How do you use usercontrols in asp.net mvc that display an "island" of data?

I am trying to find out how to use usercontrols in asp.net mvc. I know how to add a usercontrol to a view and how to pass data to it. What I haven't been able to figure out is how do you do this without having to retrieve and pass the data in every single controller?
For example, if I have a user control that displays the most recent posts on several but not all the pages in the site, how do I write the Controllers so that I get data for that usercontrol and pass it to the user control from only one place in the web site instead of getting and passing data in each of the different controllers that the user control is used in?
I'm not sure if this makes sense or not. Is there a better or recommended way to handle an "island" of data that you want to display on several pages?
I'm coming from web forms where I could just write a user control that got its own data and displayed data independently from the rest of whatever page it is used on.
There are multiple ways to do it.
The basic approach is
Populate the data for the view in the BaseController (OnActionExecuting event)
Writing a custom action filter
Writing an Application Controller (the eg. is in the below links).
An example of OnActionExecuting will be
[HandleError]
public class BaseController : Controller
{
CourseService cs = new CourseService();
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
List<Tag> tags = cs.GetTags();
ViewData["Tags"] = tags;
}
}
You can use the "tags" view data on any view. This is just an example of usercontrol being rendered as side content.
<div id="sidebar_b">
<asp:ContentPlaceHolder ID="ContentReferenceB" runat="server" >
<% Html.RenderPartial("Tags"); %>
</asp:ContentPlaceHolder>
</div>
I found the following URL to be useful.
http://weblogs.asp.net/stephenwalther/archive/2008/08/12/asp-net-mvc-tip-31-passing-data-to-master-pages-and-user-controls.aspx
http://blog.matthidinger.com/2008/02/21/ASPNETMVCUserControlsStartToFinish.aspx
http://www.aaronlerch.com/blog/2008/01/26/displaying-foo-on-every-page-of-an-aspnet-mvc-application/
http://blog.wekeroad.com/2008/01/07/aspnet-mvc-using-usercontrols-usefully/
In the MVC Futures, available on codeplex , contains the RenderAction HtmlHelper extensions. This will allow you to create a controller for the ueser control and this controller will populate the ViewData used by the user control without having to resort to a base controller as was suggested.
In the View you would do
<% Html.RenderAction("Index", "UserControlController") %>
or one of the other overloads.
This will create an instance of the controller, execute the method and render the user control view into the main view. The main view controller does not need to know anything about the user control or its model/data.
Refactor the code that obtains the view data for this user control into it's own method, maybe even it's own model (class). Call this method from each controller that needs to populate the control and pass the results in the ViewData with a well-known key. You might even want to pass the type of the current controller to your method in case it needs to know what data to retrieve based on the base model for the controller.
ViewData["RecentPosts"] = RecentPosts.GetRecentPosts( this.GetType() );
In your control, retrieve the data using the well-known key.
How to Handle "Side Content" in ASP.NET MVC

Resources