ASP.NET MVC 5 Controllers and Actions

Creating a Controller with IController

All controller classes must implemet IController interface.

    public class BasicController : IController
    {
        public void Execute(RequestContext requestContext)
        {
            string controller = (string)requestContext.RouteData.Values["controller"];
            string action = (string)requestContext.RouteData.Values["action"];
            requestContext.HttpContext.Response.Write(string.Format("Controller is {0}, action is {1}", controller, action));
        }
    }

Creating a Controller by Deriving from the Controller Class

Compared with class only implement IController interface, class derived from Controller class has three key features:

  • Action Method: A controller‘s behavior is partitioned into multiple methods (instead of having just one single Execute() method). Each method is exposed on a different URL and is invoked with parameters extracted from the incoming request.
  • Actioin Result: You can return an object describing the result of a action, which is then carried out on your behalf.
  • Filter: You can encapsulate reusable behaviors (for example, authentication) as filters, and then tag each behavior onto one or more controllers or action methods by putting an attribute in your source code.
    public class DefaultController : Controller
    {
        // GET: Default
        public ActionResult Index()
        {
            return View();
        }
    }

Receiving Request Data

There are three main way to access data:

  • Extract it from a set of context objects.
  • Have the data passed as parameters to your action method.
  • Explicitly invoke the framework’s model binding feature.

Getting Data from Context Objects, below is commonly used context objects and properties:

HttpContext.Response, HttpContext.Request, HttpContext.Session, HttpContext.User, HttpContext.Cache, HttpContext.Application, HttpContext.Items, HttpContext.Server, RouteData.Values, TempData.

Understanding Action Results

When the MVC Framework receives an ActionResult object from an action method, it calls the ExecuteResult method defined by that object. The action result implementation then deals with the Response object for you, generating the output that corresponds to your intention.

Built-in Action Result Type:

Returning HTML by Rendering a View

When the MVC Framework calls the ExecuteResult method of the ViewResult object, a search will begin for the view that you have specified. If you are using areas in your project, then the framework will look in the following locations:

? /Areas/<AreaName>/Views/<ControllerName>/<ViewName>.aspx

? /Areas/<AreaName>/Views/<ControllerName>/<ViewName>.ascx

? /Areas/<AreaName>/Views/Shared/<ViewName>.aspx

? /Areas/<AreaName>/Views/Shared/<ViewName>.ascx

? /Areas/<AreaName>/Views/<ControllerName>/<ViewName>.cshtml

? /Areas/<AreaName>/Views/<ControllerName>/<ViewName>.vbhtml

? /Areas/<AreaName>/Views/Shared/<ViewName>.cshtml

? /Areas/<AreaName>/Views/Shared/<ViewName>.vbhtml

The MVC Framework checks to see if each of these files exists in turn. As soon as it locates a match, it uses that view to render the result of the action method.

If you are not using areas, or you are using areas but none of the files in the preceding list have been found, then the framework continues its search, using the following locations:

? /Views/<ControllerName>/<ViewName>.aspx

? /Views/<ControllerName>/<ViewName>.ascx

? /Views/Shared/<ViewName>.aspx

? /Views/Shared/<ViewName>.ascx

? /Views/<ControllerName>/<ViewName>.cshtml

? /Views/<ControllerName>/<ViewName>.vbhtml

? /Views/Shared/<ViewName>.cshtml

? /Views/Shared/<ViewName>.vbhtml

Passing Data from an Action Method to a View

Providing a View Model Object

Passing Data with the View Bag

Performing Redirections

Redirecting to a Literal URL

public RedirectResult Redirect() {
    return RedirectPermanent("/Example/Index");
}

Redirecting to a Routing System URL

public RedirectToRouteResult Redirect()
{
    return RedirectToRoute(new
    {
        controller = "Example",
        action = "Index",
        ID = "MyID"
    });
}

Redirecting to an Action Method

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

A redirection causes the browser to submit an entirely new HTTP request, which means that you do not have access to the details of the original request. If you want to pass data from one request to the next, you can use the Temp Data feature. TempData is similar to Session data, except that TempData values are marked for deletion when they are read, and they are removed when the request has been processed.

public RedirectToRouteResult RedirectToRoute()
{
    TempData["Message"] = "Hello";
    TempData["Date"] = DateTime.Now;
    return RedirectToAction("Index");
}

public ViewResult Index()
{
    ViewBag.Message = TempData["Message"];
    ViewBag.Date = TempData["Date"];
    return View();
}

You can get a value from TempData without marking it for removal by using the Peek method, like this:

DateTime time = (DateTime)TempData.Peek("Date");

You can preserve a value that would otherwise be deleted by using the Keep method, like this:

TempData.Keep("Date");

The Keep method doesn’t protect a value forever. If the value is read again, it will be marked for removal once more.

Returning Errors and HTTP Codes

Sending a Specific HTTP Result Code

public HttpStatusCodeResult StatusCode()
{
    return new HttpStatusCodeResult(404, "URL cannot be serviced");
}

Sending a 404 Result

public HttpStatusCodeResult StatusCode()
{
    return HttpNotFound();
}

Sending a 401 Result

public HttpStatusCodeResult StatusCode()
{
    return new HttpUnauthorizedResult();
}
时间: 2024-12-17 12:02:38

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

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

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

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

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

ASP.NET MVC程序传值方式:ViewData,ViewBag,TempData和Session

转载原地址 http://www.cnblogs.com/sunshineground/p/4350216.html 在ASP.NET MVC中,页面间Controller与View之间主要有以下几种小量数据的传值方式:ViewData.ViewBag.TempData和Session变量. 下面就这四种传值方式做出详细介绍. 一.ViewData ViewData是一个继承自ViewDataDictionary类的Dictionary对象,它只能存储String Key/Object Valu