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

  1. public static void RegisterRoutes(RouteCollection routes)
  2. {
  3. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  4.  
  5. routes.MapRoute(
  6. "Default", // Route name
  7. "{controller}/{action}/{id}", // URL with parameters
  8. new { controller = "Home", action = "Index", id = UrlParameter.Optional }
  9. // Parameter defaults
  10. );
  11. }

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

  1. public ActionResult Index()
  2. {
  3. ViewBag.Message = string.Format("{0}---{1}--{2}",
  4. RouteData.Values["Controller"],
  5. RouteData.Values["action"],
  6. RouteData.Values["id"]
  7. );
  8.  
  9. return View();
  10. }

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

  1. public class SampleController : Controller
  2. {
  3. //
  4. // GET: /Sample/
  5.  
  6. public ActionResult Verify()
  7. {
  8. return View();
  9. }
  10. }

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

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

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

  1. public static void RegisterRoutes(RouteCollection routes)
  2. {
  3. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  4.  
  5. routes.MapRoute(
  6. "sample",
  7. "Sample/{action}",
  8. new { controller = "Sample", action = "Verify" }
  9. );

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

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

  1. routes.MapRoute(
  2. "sample",
  3. "Sample/{username}",
  4. new { controller = "Sample", action = "Verify" }
  5. );

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

Collapse | Copy Code

  1. public ActionResult Verify(string username)
  2. {
  3. return Content(username);
  4. }

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

  1. routes.MapRoute(
  2. "sample",
  3. "Sample/{username}",
  4. new { controller = "Sample", action = "Verify",
  5. username=UrlParameter.Optional }
  6. );

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

Collapse | Copy Code

  1. public ActionResult Verify(string username="all")
  2. {
  3. return Content(username);
  4. }

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.

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

  1. ASP.NET MVC中Area的另一种用法

    ASP.NET MVC中Area的另一种用法 [摘要]本文只是为一行代码而分享 context.MapRoute("API", "api/{controller}/{ac ...

  2. Post Complex JavaScript Objects to ASP.NET MVC Controllers

    http://www.nickriggs.com/posts/post-complex-javascript-objects-to-asp-net-mvc-controllers/     Post ...

  3. ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库

    在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...

  4. ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第一章:创建基本的MVC Web站点

    在这一章中,我们将学习如何使用基架快速搭建和运行一个简单的Microsoft ASP.NET MVC Web站点.在我们马上投入学习和编码之前,我们首先了解一些有关ASP.NET MVC和Entity ...

  5. ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之目录导航

    ASP.NET MVC with Entity Framework and CSS是2016年出版的一本比较新的.关于ASP.NET MVC.EF以及CSS技术的图书,我将尝试着翻译本书以供日后查阅. ...

  6. ASP.NET MVC——模型绑定

    这篇文章我们来讲讲模型绑定(Model Binding),其实在初步了解ASP.NET MVC之后,大家可能都会产生一个疑问,为什么URL片段最后会转换为例如int型或者其他类型的参数呢?这里就不得不 ...

  7. ASP.NET MVC 使用 Petapoco 微型ORM框架+NpgSql驱动连接 PostgreSQL数据库

    前段时间在园子里看到了小蝶惊鸿 发布的有关绿色版的Linux.NET——“Jws.Mono”.由于我对.Net程序跑在Linux上非常感兴趣,自己也看了一些有关mono的资料,但是一直没有时间抽出时间 ...

  8. 你从未知道如此强大的ASP.NET MVC DefaultModelBinder

    看到很多ASP.NET MVC项目还在从request.querystring或者formContext里面获取数据,这实在是非常落后的做法.也有的项目建了大量的自定义的modelbinder,以为很 ...

  9. ASP.NET MVC Model验证(一)

    ASP.NET MVC Model验证(一) 前言 前面对于Model绑定部分作了大概的介绍,从这章开始就进入Model验证部分了,这个实际上是一个系列的Model的绑定往往都是伴随着验证的.也会在后 ...

随机推荐

  1. Linux 下.desktop 桌面程序图标文件编写方式

    [Desktop Entry] //每个desktop文件都以这个标签开始,说明这是一个Desktop Entry文件 Version = 1.0 //标明Desktop Entry的版本(可选) N ...

  2. 腾讯 Bugly for Xamarin Android 的插件

    因为项目中需要异常控制,所以在 gpyer bugly 等 Bug 收集平台中选择,最后选定了 Bugly. 于是将 Bugly 的插件 进行了 Java Binding,打成了 Xamarin 可用 ...

  3. 【Windows编程】系列第二篇:Windows SDK创建基本控件

    在Win32 SDK环境下,怎么来创建常用的那些基本控件呢?我们知道如果用MFC,简单的拖放即可完成大多数控件的创建,但是我们既然是用Windows SDK API编程,当然是从根上解决这个问题,实际 ...

  4. [WPF系列]-参考文献

      DataTemplates Data Templating Overview Styling and Templating DataTemplate Class FrameworkTemplate ...

  5. .Net 扩展方法集合.

      在项目中很多时候都会对字符串和集合做特定的处理.而且很多地方都会去调用.为了解决这些问题.我们通常会在项目中吧这些方法提成公共方法.下面是自己总结的项目中用到的一些扩展方法.封装成了一个Libra ...

  6. 一个"如何使用示波器安全测试接市电电路板"的问题

    最近犯了一个错误测试操作: 测试场景:直接从市电插座取电接入3W非隔离开关电源电路板,使用示波器测试输出电压,此时示波器通过另外一个插座直接从市电取电 测试后果:在将示波器接到输出负极的一瞬间,漏电保 ...

  7. golang中的slice翻转存在以及map中的key判断

    //slice翻转 func stringReverse(src []string){ if src == nil { panic(fmt.Errorf("the src can't be ...

  8. winform记事本(基本功能)

    本题主要考察各种控件的应用 using System; using System.Collections.Generic; using System.ComponentModel; using Sys ...

  9. Confluence Wiki -- 页面限制

    Confluence Wiki 中 [页面设置] 应该如何理解? 当一个用户有这个权限后,这个用户可以对一个页面做限制,可以限制这个页面不能被其他用户浏览或编辑: 反之,如果没有这个权限,那么这个用户 ...

  10. PAT 1040. 有几个PAT(25)

    字符串APPAPT中包含了两个单词"PAT",其中第一个PAT是第2位(P),第4位(A),第6位(T):第二个PAT是第3位(P),第4位(A),第6位(T). 现给定字符串,问 ...