ASP.NET MVC - code behind the main pages

I am new to ASP.NET MVC 1.0. I am converting from a classic application created using VS2008.NET3.5. I created the main page and the menu should be read from the database. Now the code that generates HTML in the appropriate div unit in the classic ASP.NET3.5 VS2008 was in the code behind the main page.

Now I can’t understand where the lead page code is in ASP.NET MVC 1.0?

Anyone have any examples?

thanks

+6
asp.net-mvc code-behind
source share
5 answers

MVC no longer has Code-Behind classes. What you want is partial.

You would use it like this:

<% Html.RenderPartial("MainMenu.ascx", ViewData["Menu"]); %> 

If this menu is on all your pages, you can make your controller a subclass of the user controller class, which first populates the menu data.

If you mess around with the MVC inheritance hierarchy too, you can also create the MenuController class and use the RenderAction in your view / wizard:

 <% Html.RenderAction<MenuController>(x => x.MainMenu()); %> 
+7
source share

You still have the code if you want. In the .master file, enter:

 <%@ 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) { } } 
+6
source share

Your main page is now a presentation, and the presentation should be passive. In other words, they should not look for things themselves.

This would be a much more correct approach (in 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.

+3
source share

The ASP.NET section has a great tutorial that shows how to do this.

In short, you transfer data to the main page through the ViewData collection. To get data in ViewData, create an application-level controller. Page controllers inherit from the application controller instead of the base MVC controller.

In addition, if you need to do something on your main page in response to the page being displayed, through this application controller you can bind the ActionExecuting event. This will provide you with information about the context of the current page request.

+3
source share

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

+1
source share

All Articles