【转】Controllers and Routers in ASP.NET MVC 3

Controllers and Routers in ASP.NET MVC 3

ambilykk, 3 May 2011 CPOL

4.79 (23 votes)

Rate:

vote 1vote 2vote 3vote 4vote 5

A deeper look into the two pillars of ASP.NET MVC – Routers and Controllers.

Introduction

ASP.NET MVC provides a new way of creating web applications which is more extensible and testable. We discussed about ASP.NET MVC in Introduction to ASP.NET MVC 3. Here, we will have a deeper look into the two pillars of ASP.NET MVC – Routers and Controllers.

Routers

One of the main objectives of ASP.NET MVC is Search Engine Optimization (SEO). Search Engines work mainly using URLs. Defining a meaningful and more understandable URL is very important to make our application more search engine friendly.

Routing is the way of constructing meaningful URLs for a web request. As you have already seen, our MVC application URLs are not represented by extensions like .aspx. Instead, the URLs consist of the Controller name and Action name.

Let us first understand how the default routing works. Open the Global.ascx file, and we can see theApplication_Start() and RegisterRoute() methods.

Collapse | Copy Code

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            // Parameter defaults
    );
}

Look at the statement where we map the routing. Our URL formation uses the pattern “{controller}/{action}/{id}", where id is an optional parameter.

new { controller = "Home", action = "Index", id = UrlParameter.Optional } specifies that in case the URL does not specify a Controller, use the Home Controller. Also, in the absence of an Action, it uses the Index action, and the last parameter is Optional.

Routing data inside a Controller

We can access routing data inside a Controller using the RouteData object.

Collapse | Copy Code

public ActionResult Index()
{
    ViewBag.Message = string.Format("{0}---{1}--{2}",
        RouteData.Values["Controller"],
        RouteData.Values["action"],
        RouteData.Values["id"]
        );

    return View();
}

Controllers

Now let us create a new Controller and see how we can route to the new Controller using a different routing pattern.

Add a new Controller using Add New Item -> Controller. It adds a new Controller with an Action as Index. For our sample application, we are using a different Action called Verify.

Collapse | Copy Code

public class SampleController : Controller
{
    //
    // GET: /Sample/

    public ActionResult Verify()
    {
        return View();
    }
}

As there are no Views corresponding to SampleController, let us return some text from our Action. For returning any text data from an Action, use the Content class.

Collapse | Copy Code

public ActionResult Verify()
{
    return Content("Hello From Sample Controller.");
}

Let us run the application. Modify the URL to /sample/verify.

But if we specify /Sample without any Action, we will receive a 404 error. As per the defined routing, if there is no Action specified, it should redirect to the Index action inside the specified Controller. Here, our SampleControllerdoesn’t have any Index action and throws an error.

Adding a new route

For fixing the above issue, let us define a new route called “sample”.

Collapse | Copy Code

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
                "sample",
                "Sample/{action}",
                new { controller = "Sample", action = "Verify" }
                );

   // 这个一定要放在Default前面,否则会找不到
    routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index",
                      id = UrlParameter.Optional } // Parameter defaults
            );

}

Now we may need to pass some data to our new Controller from a URL, like the id parameter in the default routing. For that, define a new parameter in the routing.

Collapse | Copy Code

routes.MapRoute(
                "sample",
                "Sample/{username}",
                new { controller = "Sample", action = "Verify" }
                );

The value can be accessed either using the RouteData object or through a parameter to the Verify action.

Collapse | Copy Code

public ActionResult Verify(string username)
{
    return Content(username);
}

Note that the URL consists of only the Controller and the parameter.

Again, you will receive a 404 error when we omit the parameter value.

For solving this issue, we need to specify the default value for the username parameter either in the Route mapping or in the Controller.

In the route map, specify the parameter as optional.

Collapse | Copy Code

routes.MapRoute(
                "sample",
                "Sample/{username}",
                new { controller = "Sample", action = "Verify",
                      username=UrlParameter.Optional }
                );

Inside the Controller, specify the default value for the parameter.

Collapse | Copy Code

public ActionResult Verify(string username="all")
{
    return Content(username);
}

Conclusion

We had a quick discussion on how routing works in ASP.NET MVC and how we can customize the same. We will discuss more about Views, Styles, Action results, etc., in the next article.

时间: 2024-08-28 23:35:34

【转】Controllers and Routers in ASP.NET MVC 3的相关文章

Post Complex JavaScript Objects to ASP.NET MVC Controllers

http://www.nickriggs.com/posts/post-complex-javascript-objects-to-asp-net-mvc-controllers/     Post Complex JavaScript Objects to ASP.NET MVC Controllers Posted in ASP.NET'JavaScript August 21, 2009 Use the plug-in postify.js to handle posting comple

ASP.NET MVC 4入门

一.MVC设计模式将Web应用分解成三个部分:模型(Models).试图(Views)和控制器(Controllers),这三部分分别完成不同的功能以实现Web应用. 视图(View)代表用户交互界面,对于Web应用来说,可以概括为HTML界面,但有可能为XHTML.XML和Applet.MVC设计模式对于视图的处理仅限于视图上数据的采集和处理,以及用户的请求,不包括在视图上的业务流程的处理.业务流程的处理交予模型(Model)处理. 模型(Model)就是业务流程/状态的处理以及业务规则的制定

CRUD Operations In ASP.NET MVC 5 Using ADO.NET

Background After awesome response of an published by me in the year 2013: Insert, Update, Delete In GridView Using ASP.Net C#. It now has more than 140 K views, therefore to help beginners I decided to rewrite the article i with stepbystep approach u

Asp.Net MVC 插件化开发简化方案

Web 管理系统可以庞大到不可想像的地方,如果想就在一个 Asp.Net MVC 项目中完成开发,这个工程将会变得非常庞大,协作起来也会比较困难.为了解决这个问题,Asp.Net MVC 引入了 Areas 的概念,将模块划分到 Area 中去--然而 Area 仍然是主项目的一部分,多人协作的时候仍然很容易造成 .csproj 项目文件的冲突. 对于这类系统,比较好的解决办法是采用 SOA 的方式,把一个大的 Web 系统划分成若干微服务,通过一个含授权中心的 Web 集散框架组织起来.不过这

ASP.NET MVC框架下添加菜单栏及分页项目

原创声明:本文为作者原创,转载请注明出处:http://www.cnblogs.com/DrizzleWorm/p/7274866.html ,谢谢! 我是做前端开发的,之前用C#的三层架构(UI.BLL.DAL)做过一个网站,这是我第一次接触ASP.NET MVC框架,首先给大家分享别人整理的ASP.NET MVC框架的一组教程:http://www.cnblogs.com/powertoolsteam/archive/2015/08/13/4667892.html内容很齐全,我是在先看了其他

asp.net mvc 使用Ajax调用Action 返回数据【转】

使用asp.net mvc 调用Action方法很简单. 一.无参数方法. 1.首先,引入jquery-1.5.1.min.js 脚本,根据版本不同大家自行选择. <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script> 2.在Controllers中书写前台Ajax需要调用的Action,比如:

ASP.NET MVC5(一):ASP.NET MVC概览

ASP.NET MVC概览 ASP.NET MVC是一种构建Web应用程序的框架,它将一般的MVC(Model-View-Controller)模式应用于ASP.NET框架. ASP.NET MVC模式简介 MVC将Web应用程序划分为三个主要的部分,以下是MSDN给出的定义: 模型(Model):模型对象是实现应用程序数据域逻辑的应用程序部件. 通常,模型对象会检索模型状态并将其存储在数据库中. 例如,Product 对象可能会从数据库中检索信息,操作该信息,然后将更新的信息写回到 SQL S

ASP.NET MVC概述及第一个MVC程序

一.ASP.NET 概述        1. .NET Framework 与 ASP.NET                .NET Framework包含两个重要组件:.NET Framework类库和公共语言进行时.编写ASP.NET                    页面需要用到.NET Framework的框架类库和公共语言进行时        2. ASP.NET MVC简介            ASP.NET MVC是ASP.NET技术的一个子集,它是ASP.NET 技术和M

ASP.NET MVC Web API 学习笔记---Web API概述及程序示例

1. Web API简单说明 近来很多大型的平台都公开了Web API.比如百度地图 Web API,做过地图相关的人都熟悉.公开服务这种方式可以使它易于与各种各样的设备和客户端平台集成功能,以及通过在浏览器中使用 JavaScript来创建更丰富的HTML体验.所以我相信Web API会越来越有它的用武之地. 说道Web API很多人都会想到Web服务,但是他们仍然有一定的区别:Web API服务是通过一般的 HTTP公开了,而不是通过更正式的服务合同 (如SOAP) 2. ASP.NET W