MVC应用程序里的URL请求是通过控制器Controller处理的,不管是请求视图页面的GET请求,还是传递数据到服务端处理的Post请求都是通过Controller来处理的,先看一个简单的Controlller:

public class DerivedController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Hello from the DerivedController Index method"; //动态数据
return View("MyView"); //指定返回的View
}
}

是个DerivedController,那么对应处理的URL就是这样的:localhost:1042/Derived/Index,并且Index这个Action指定了返回的视图是MyView,而不是同名的Index视图,那么就需要新建一个视图MyView。在Index这个Action方法内右键 - 添加视图 - MyView,或者在解决方案的Views目录下新建一个Derived目录,再右键 - 新建视图 - MyView:

@{
ViewBag.Title = "MyView";
}
<h2>
MyView</h2>
Message: @ViewBag.Message

直接Ctrl+F5运行程序浏览器定位到的url是:localhost:1042,看看路由的定义:

routes.MapRoute(
"Default", // 路由名称
"{controller}/{action}/{id}", // 带有参数的 URL
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
);

注意路由的最后一行:new { controller = "Home", action = "Index", id = UrlParameter.Optional }
都给默认值了,那么URL:localhost:1042 其实就是:localhost:1042/Home/Index id是可选参数。
localhost:1042/Home/Index这个Url找的Controller自然是HomeController,Index对应的是HomeController下的Index这个Action,显然没有HoomeController,自然会报404错。
解决方法:
1.把路由的默认值修改成:

new { controller = "Derived", action = "Index", id = UrlParameter.Optional }

2.在浏览器的url栏里手动输入:localhost:1042/Derived/index

可以通过上下文对象Context取一些参数:

string userName = User.Identity.Name;
string serverName = Server.MachineName;
string clientIP = Request.UserHostAddress;
DateTime dateStamp = HttpContext.Timestamp;

跟普通的WebForm里一样,可以通过Request.Form接收传递过来的参数:

string oldProductName = Request.Form["OldName"];
string newProductName = Request.Form["NewName"];

取URL里/路由的参数:

string city = RouteData.Values["city"].ToString();

给Controller传参:

public ActionResult ShowWeatherForecast(string city, DateTime forDate)
{
ViewBag.City = city;
ViewBag.ForDate = forDate;
return View();
}

对应的a标签是这样的:
@Html.ActionLink("查看天气(传参)", "ShowWeatherForecast", new { city = "北京", forDate = @DateTime.Now })
再添加对应的视图:

@{
Layout = null;
}
要查询的是:@ViewBag.City 的天气,查询的时间是:@ViewBag.ForDate

运行下程序ShowWeatherForecast视图就显示了:
要查询的是:北京 的天气,查询的时间是:2013/11/25 21:08:04

当然也可以不传参但是提供默认值:

@Html.ActionLink("查看天气(默认值) ", "ShowWeatherForecast", new { forDate = @DateTime.Now })

没有传city,看Controller:

public ActionResult ShowWeatherForecast(DateTime forDate, string city = "合肥")
{
ViewBag.City = city;
ViewBag.ForDate = forDate;
return View();
}

视图显示:
要查询的是:合肥 的天气,查询的时间是:2013/11/25 21:16:35
默认值已经起作用了。

控制器里获取路由数据:

public string Index()
{
string controller = (string)RouteData.Values["controller"];
string action = (string)RouteData.Values["action"]; return string.Format("Controller: {0}, Action: {1}", controller, action);
}

自然浏览器就会显示:Controller: Derived, Action: index
Action里实现跳转:

public void Index()
{
Response.Redirect("/Derived/ShowWeatherForecast");
}

使用Response.Redirect实现跳转还比较偏WebForm化,MVC里更应该这么跳转:

public ActionResult Index()
{
return new RedirectResult("/Derived/ShowWeatherForecast");
}

之前都是类似的Action都是Return的View这里却Return的却是RedirectResult,这就得看方法的返回值了,方法的返回值是ActionResult,并不仅仅是ViewResult,可以理解为ActionResult是ViewResult和RedirectResult等等的基类。
这里甚至可以直接返回视图文件的物理路径:

return View("~/Views/Derived/ShowWeatherForecast.cshtml");

常用的Action返回值类型有:

跳转到别的Action:

public RedirectToRouteResult Redirect() {
return RedirectToAction("Index");
}

上面的方法是跳转到当前Controller下的另外一个Action,如果要跳转到别的Controller里的Action:

return RedirectToAction("Index", "MyController"); 

返回普通的Text数据:

public ContentResult Index() {
string message = "This is plain text";
return Content(message, "text/plain", Encoding.Default);
}

返回XML格式的数据:

public ContentResult XMLData() { 

    StoryLink[] stories = GetAllStories(); 

    XElement data = new XElement("StoryList", stories.Select(e => {
return new XElement("Story",
new XAttribute("title", e.Title),
new XAttribute("description", e.Description),
new XAttribute("link", e.Url));
})); return Content(data.ToString(), "text/xml");
}

返回JSON格式的数据(常用):

[HttpPost]
public JsonResult JsonData() { StoryLink[] stories = GetAllStories();
return Json(stories);
}

文件下载:

public FileResult AnnualReport() {
string filename = @"c:\AnnualReport.pdf";
string contentType = "application/pdf";
string downloadName = "AnnualReport2011.pdf"; return File(filename, contentType, downloadName);
}

触发这个Action就会返回一个文件下载提示:

返回HTTP状态码:

//404找不到文件
public HttpStatusCodeResult StatusCode() {
return new HttpStatusCodeResult(, "URL cannot be serviced");
} //404找不到文件
public HttpStatusCodeResult StatusCode() {
return HttpNotFound();
} //401未授权
public HttpStatusCodeResult StatusCode() {
return new HttpUnauthorizedResult();
}

返回RSS订阅内容:

public RssActionResult RSS() {
StoryLink[] stories = GetAllStories();
return new RssActionResult<StoryLink>("My Stories", stories, e => {
return new XElement("item",
new XAttribute("title", e.Title),
new XAttribute("description", e.Description),
new XAttribute("link", e.Url));
});
}

触发这个Action就会浏览器机会显示:

本文源码

系列文章导航

ASP.NET MVC Controllers and Actions的更多相关文章

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

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

  2. 第十五章 提升用户体验 之 设计实现MVC controllers 和 actions

    1. 概述 controllers 和 actions 是 ASP.NET MVC4中非常重要的组成部分. controller管理用户和程序间的交互,使用action作为完成任务的方式. 如果是包含 ...

  3. [引]ASP.NET MVC 4 Content Map

    本文转自:http://msdn.microsoft.com/en-us/library/gg416514(v=vs.108).aspx The Model-View-Controller (MVC) ...

  4. ASP.NET MVC HttpVerbs.Delete/Put Routes not firing

    原文地址: https://weblog.west-wind.com/posts/2015/Apr/09/ASPNET-MVC-HttpVerbsDeletePut-Routes-not-firing ...

  5. 【转】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 ...

  6. 《Entity Framework 6 Recipes》中文翻译系列 (20) -----第四章 ASP.NET MVC中使用实体框架之在MVC中构建一个CRUD示例

    翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 第四章  ASP.NET MVC中使用实体框架 ASP.NET是一个免费的Web框架 ...

  7. 7、ASP.NET MVC入门到精通——第一个ASP.NET MVC程序

    本系列目录:ASP.NET MVC4入门到精通系列目录汇总 开发流程 新建Controller 创建Action 根据Action创建View 在Action获取数据并生产ActionResult传递 ...

  8. ASP.NET MVC 多语言实现——URL路由

    考虑实现一个完整的基于asp.net mvc的多语言解决方案,从路由到model再到view最后到数据库设计(先挖好坑,后面看能填多少). 我所见过的多语言做得最好的网站莫过于微软的msdn了,就先从 ...

  9. 使用ASP.NET MVC操作过滤器记录日志(转)

    使用ASP.NET MVC操作过滤器记录日志 原文地址:http://www.singingeels.com/Articles/Logging_with_ASPNET_MVC_Action_Filte ...

随机推荐

  1. 总结项目开发中用到的一些css\html技巧

    这篇就是用来总结记录的,会长期更新. 1,半透明背景效果(#ffffff颜色的半透明背景): font-style: italic;">#ffffff; filter:alpha(op ...

  2. 【Win 10 应用开发】通过数据绑定更新进度条

    实现 INotifyPropertyChanged 接口可以在属性更改后通知数据的使用者,这个相信大伙儿都知道.于是,有朋友会问:对于要实时显示进度的情况,比如更新进度条,能用这个实现吗? 当然是可以 ...

  3. ASP.NET MVC5+EF6+EasyUI 后台管理系统(42)-工作流设计-表建立

    系列目录 工作流在实际应用中还是比较广泛,网络中存在很多工作流的图形化插件,可以做到拉拽的工作流设计,非常简便,再配合第三方编辑器,可以直接生成表单,我没有刻意的浏览很多工作流的实际设计,我认为工作流 ...

  4. spring源码分析之<context:component-scan/>vs<annotation-config/>

    1.<context:annotation-config/> xsd中说明: <xsd:element name="annotation-config"> ...

  5. 门面模式的典型应用 Socket 和 Http(post,get)、TCP/IP 协议的关系总结

    门面模式的一个典型应用:Socket 套接字(Socket)是通信的基石,是支持TCP/IP协议的网络通信的基本操作单元.它是网络通信过程中端点的抽象表示,包含进行网络通信必须的五种信息: 连接使用的 ...

  6. jeffy-vim-v3.0

    jeffy-vim-v3.0 修改了配色.

  7. Unity3D移动平台动态读取外部文件全解析

    前言: 一直有个想法,就是把工作中遇到的坑通过自己的深挖,总结成一套相同问题的解决方案供各位同行拍砖探讨.眼瞅着2015年第一个工作日就要来到了,小匹夫也休息的差不多了,寻思着也该写点东西活动活动大脑 ...

  8. 使控件具有 Tilt 效果

    步骤1:添加类: /* Copyright (c) 2010 Microsoft Corporation. All rights reserved. Use of this sample source ...

  9. 11 个很少人知道但很有用的 Linux 命令

    Linux命令行吸引了大多数Linux爱好者.一个正常的Linux用户一般掌握大约50-60个命令来处理每日的任务.Linux命令和它们的转换对于Linux用户.Shell脚本程序员和管理员来说是最有 ...

  10. ManualResetEvent知识总结

    一. 用法概述 Manual发音:英[ˈmænjuəl] 直译,手动重置事件 开发者的可以手动对线程间的交互进行手动控制. 二.构造函数 构造函数,如果为 true,则将初始状态设置为终止:如果为 f ...