码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET MVC 5 Controllers and Actions

时间:2017-05-13 12:28:39      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:ecif   context   basic   exists   out   als   hello   route   ram   

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();
}

 

ASP.NET MVC 5 Controllers and Actions

标签:ecif   context   basic   exists   out   als   hello   route   ram   

原文地址:http://www.cnblogs.com/liangzi4000/p/6842314.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!