ASP.NET MVC Controllers and Actions

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(404, "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就会浏览器机会显示:

时间: 2024-10-21 19:35:53

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

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 HttpVerbs.Delete/Put Routes not firing

原文地址: https://weblog.west-wind.com/posts/2015/Apr/09/ASPNET-MVC-HttpVerbsDeletePut-Routes-not-firing?utm_source=tuicool&utm_medium=referral 国内:http://www.tuicool.com/articles/Zv2EbmY A few times in the last weeks I’ve run into a problem where I found

【转】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 creati

Professional C# 6 and .NET Core 1.0 - Chapter 41 ASP.NET MVC

What's In This Chapter? Features of ASP.NET MVC 6 Routing Creating Controllers Creating Views Validating User Inputs Using Filters Working with HTML and Tag Helpers Creating Data-Driven Web Applications Implementing Authentication and Authorization W

ASP.NET MVC WebGrid &ndash; Performing true AJAX pagination and sorting 【转】

ASP.NET MVC WebGrid – Performing true AJAX pagination and sorting FEBRUARY 27, 2012 14 COMMENTS WebGrid is a very powerful HTML helper component introduced with ASP.NET MVC 3 and ASP.NET Web Pages. Despite all its cool features, it is troublesome to

Ninject之旅之十三:Ninject在ASP.NET MVC程序上的应用

摘要: 在Windows客户端程序(WPF和Windows Forms)中使用Ninject和在控制台应用程序中使用Ninject没什么不同.在这些应用程序里我们不需要某些配置用来安装Ninject,因为在Windows客户端应用程序里,开发者可以控制UI组件的实例化(Forms或Windows),可以很容易地委托这种控制到Ninject.然而在Web应用程序里,就不同了,因为框架负责了实例化UI元素.因此,我们需要知道怎样告诉框架委托这种控制责任给Ninject.幸运的是,让ASP.NET M

LowercaseRoutesMVC ASP.NET MVC routes to lowercase URLs

About this Project Tired of your MVC application generating mixed-case URLs like http://mysite.com/Home/About orhttp://mysite.com/Admin/Customers/List? Wouldn't http://mysite.com/home/about andhttp://mysite.com/admin/customers/list be a lot nicer? I

Asp.Net MVC中使用ACE模板之Jqgrid

第一次看到ACE模板,有种感动,有种相见恨晚的感觉,于是迅速来研究.它本身是基于bootstrap和jqueryui,但更nice,整合之后为后台开发节省了大量时间. 发现虽然不是完美,整体效果还是不错,特此分享给园友.这一节先讲其中的Jqgrid.按照国际惯例,先上两张图. 集成了button,form,treeview以及日历,时间轴.chart等控件,非常丰富.下面是Jqgrid在MVC中的使用. jqgrid的加载,排序,查找都是基于后台方法,不是在内存中完成,但也有一些小坑.下面一一道

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

考虑实现一个完整的基于asp.net mvc的多语言解决方案,从路由到model再到view最后到数据库设计(先挖好坑,后面看能填多少). 我所见过的多语言做得最好的网站莫过于微软的msdn了,就先从模仿它的路由开始 仅实现相同的url格式很简单,只要将默认的路由加上一个表示语言的变量就可以了 public static void RegisterRoutes(RouteCollection routes) { //other routes routes.MapRoute( name: "Def