【转】Controllers and Routers in ASP.NET MVC 3
Controllers and Routers in ASP.NET MVC 3
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 SampleController
doesn’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.
【转】Controllers and Routers in ASP.NET MVC 3的更多相关文章
- ASP.NET MVC中Area的另一种用法
ASP.NET MVC中Area的另一种用法 [摘要]本文只是为一行代码而分享 context.MapRoute("API", "api/{controller}/{ac ...
- Post Complex JavaScript Objects to ASP.NET MVC Controllers
http://www.nickriggs.com/posts/post-complex-javascript-objects-to-asp-net-mvc-controllers/ Post ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库
在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第一章:创建基本的MVC Web站点
在这一章中,我们将学习如何使用基架快速搭建和运行一个简单的Microsoft ASP.NET MVC Web站点.在我们马上投入学习和编码之前,我们首先了解一些有关ASP.NET MVC和Entity ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之目录导航
ASP.NET MVC with Entity Framework and CSS是2016年出版的一本比较新的.关于ASP.NET MVC.EF以及CSS技术的图书,我将尝试着翻译本书以供日后查阅. ...
- ASP.NET MVC——模型绑定
这篇文章我们来讲讲模型绑定(Model Binding),其实在初步了解ASP.NET MVC之后,大家可能都会产生一个疑问,为什么URL片段最后会转换为例如int型或者其他类型的参数呢?这里就不得不 ...
- ASP.NET MVC 使用 Petapoco 微型ORM框架+NpgSql驱动连接 PostgreSQL数据库
前段时间在园子里看到了小蝶惊鸿 发布的有关绿色版的Linux.NET——“Jws.Mono”.由于我对.Net程序跑在Linux上非常感兴趣,自己也看了一些有关mono的资料,但是一直没有时间抽出时间 ...
- 你从未知道如此强大的ASP.NET MVC DefaultModelBinder
看到很多ASP.NET MVC项目还在从request.querystring或者formContext里面获取数据,这实在是非常落后的做法.也有的项目建了大量的自定义的modelbinder,以为很 ...
- ASP.NET MVC Model验证(一)
ASP.NET MVC Model验证(一) 前言 前面对于Model绑定部分作了大概的介绍,从这章开始就进入Model验证部分了,这个实际上是一个系列的Model的绑定往往都是伴随着验证的.也会在后 ...
随机推荐
- 设计模式C#实现(十五)——命令模式
意图 0 适用性 1 结构 2 实现 3 效果 4 参考 5 意图 将请求封装成一个对象,客户接受请求参数:可以对请求排队或者记录请求日志,以及可以支持撤销操作 适用性 抽象出待执行的动作以参数化某对 ...
- Maven 的classifier的作用
直接看一个例子,maven中要引入json包,于是使用了 <dependency> <groupId>net.sf.json-lib</groupId> <a ...
- mycat高可用方案
1.建议采用标准的mysql主从复制高可用配置并交付给mycat来完成后端mysql节点的主从自动切换. 2.mycat自身的高可用性 由HAproxy+Mycat集群+Mysql主从所组成的高可用性 ...
- linux(64位的系统)下nasm进行汇编链接时出现的问题
出现问题: $nasm -f elf hello.asm -o hello.o $ld -s hello.o -o hello ld: i386 architecture of input file ...
- [WPF系列]-数据邦定之DataTemplate 对分层数据的支持
到目前为止,我们仅讨论如何绑定和显示单个集合. 某些时候,您要绑定的集合包含其他集合. HierarchicalDataTemplate 类专用于 HeaderedItemsControl 类型以显示 ...
- Selenium2(WebDriver)_如何判断WebElement元素对象是否存在
1. selenium中如果去寻找元素,而元素不存在的话,通常会抛出NoSuchElementException 导致测试失败,但有时候,我们需要去确保页面元素不存在,才是我们正确的验收条件下面的方法 ...
- PHP_Bibel阅读笔记(二)——脸黑的一天(?一年)
一早上起来把50包开了,一张橙卡...就问还有谁...........本命年啊,我去买红内裤还不行么.... 实时更新,老哥的号的30包什么都没有....不过中午又开了5包,皇帝,好评啊!!! 五.代 ...
- 【Bootstrap Demo】入门例子创建
本文简单介绍下如何来使用 Bootstrap,通过引入 Bootstrap,来实现一个最基本的入门例子. 在前一篇博文[Bootstrap]1.初识Bootstrap 基础之上,我们完全可以更加方便快 ...
- 解决某些Android Permission denied
最近遇到一个问题,总是在模拟器重报Permission denied错误,于是我直接在手机上测试,发现没有错误,于是很郁闷,反复在AndroidManifest中加入权限 <uses-per ...
- Linux(CentOs6.4)安装Git
安装之前我们先来了解下git,并且要反问下:我为什么要使用git?svn用的不是很好嘛,我干嘛要换?... 问1:为什么需要版本控制系统? 版本控制是一种记录若干文件内容变化,以便将来查阅特定版本修订 ...