开发者

Base page in MVC 2

开发者 https://www.devze.com 2023-01-16 11:21 出处:网络
I have just moved over to using ASP.NET MVC 2.In web forms, I normally had a BasePage class that extends from System.Web.UI.Page.And then every page extend开发者_StackOverflow社区s from this BasePage.

I have just moved over to using ASP.NET MVC 2. In web forms, I normally had a BasePage class that extends from System.Web.UI.Page. And then every page extend开发者_StackOverflow社区s from this BasePage. In this BasePage class I have methods that I need. How would I do this in an MVC application?

Any samples would be appreciated.

Thanks.


It is a bit different in MVC. The equivallent would be BaseController although this doesn't correlate exactly to a page in the classic ASP.NET sense. For a start, a controleler doesn't have any markup.

Into a base controller you might inject any model classes that are required by all pages and any common behaviours that have to be executed as part of all Action requests. An example might be some custom checks to go into the Controller OnActionExecuting event...

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onactionexecuting.aspx

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //check the filterContext for a certain condition
        if (condition) {
            //do something else - redirect to a different route or 
            //render a different view to to the default
            filterContext.Result = new RedirectResult(newUrl); 
        }
        //Otherwise, do nothing, the requested Action will execute as normal...
    }


IN MVC there is a greater separation of concerns for rendering the UI, so depending on what the code did in your base page will dictate where it goes in MVC.

If your code generated HTML than you will probably be creating custom HTML helpers and reusable partials views (.ascx). If it handled input data than it will go in a model binder class, and you can create a base model binder for common code. If it talked to your services and domain model than it will go in the controller, and again you can use a base controller. Queries to the persistence layer will go in your model, and reusing code here leads to a much larger discussion of your architecture.


We also moved from base Page classes in ASP.NET and found that a combination of a base controller and a base Model (ViewData) class works well.

So ex Page properties eg: CurrentUser are available from the base Controller and also passed to the base ViewData when its initiated so you can use them on the aspx page.

0

精彩评论

暂无评论...
验证码 换一张
取 消