Monday, 28 January 2013

ASP.NET MVC Controller and Actions


Controllers are classes which are responsible for processing incoming requests, performing operations on the domain model, and selecting views to render to the user.

Controller classes must implement the IController interface from the
System.Web.Mvc namespace.

public interface IController {
void Execute(RequestContext requestContext);
}

The base class for all controllers is the ControllerBase class, which provides general MVC handling. The Controller class inherits from ControllerBase and is the default implement of a controller. The Controller class is responsible for the following processing stages:

Locating the appropriate action method to call and validating that it can be called.

Getting the values to use as the action method's arguments.

Handling all errors that might occur during the execution of the action method.

Providing the default WebFormViewEngine class for rendering ASP.NET page types (views).

All controller classes must be named by using the "Controller" suffix.

Main features of controller:
• Action methods: Action method is exposed on a different URL and is invoked with parameters extracted from the incoming request.
• Action results: Action methods return an instance of a class that derives from ActionResult. The ActionResult class is the base for all action results.
• Filters: You can encapsulate reusable behaviors as filters, and then tag each behavior onto one or more controllers or action methods by putting an [Attribute] in your source code.
  

Actions Methods: Action method typically map with user interaction.  When user requests a URL, the MVC use the route to determine controller and action method to handle the request. Most action method returns an instance of ActionResult.

Receiving Input: Controllers access incoming data, such as query string values, form values, and parameters parsed from the incoming URL by the routing system.

Commonly Used Context Objects use to get data are:
Property Type Description
Request.QueryString NameValueCollection GET variables sent with this request
Request.Form NameValueCollection POST variables sent with this request
Request.Cookies HttpCookieCollection Cookies sent by the browser with this
Request.HttpMethod string The HTTP method (verb, such as GET or POST) used for this request
Request.Headers NameValueCollection The full set of HTTP headers sent with this request.
Request.Url Uri The URL requested
Request.UserHostAddress string The IP address of the user making this
RouteData.Route RouteBase The chosen RouteTable.Routes entry for this request
RouteData.Values RouteValueDictionary Active route parameters (either extracted from the URL or default values)
HttpContext.Application HttpApplicationStateBase Application state store
HttpContext.Cache Cache Application cache store
HttpContext.Items IDictionary State store for the current request
HttpContext.Session HttpSessionStateBase State store for the visitor’s session
User IPrincipal Authentication information about the logged-in user
TempData TempDataDictionary Temporary data items stored for the current user

Action Methods Parameters:

Value-type parameters are compulsory. To make them optional, either specify a default value or change the parameter type to a nullable type, so the MVC Framework can pass null if no value is available.

Reference-type parameters are optional. To make them compulsory (to ensure that a non-null value is passed), add some code to the top of the action method to reject null values.

ActionResult Return Type: ActionResult class is the base for all action results. However, there are different action result types, depending on the task that the action method is performing. The most common action is to call the View method. The View method returns an instance of the ViewResult class, which is derived from ActionResult.
The following table shows the built-in action result types and the action helper methods that return them.


Action Result
Helper Method
Description
ViewResult View Renders a view as a Web page.
PartialViewResult PartialView Renders a partial view, which defines a section of a view that can be rendered inside another view.
RedirectResult Redirect Redirects to another action method by using its URL.
RedirectToRouteResult RedirectToAction
RedirectToRoute
Redirects to another action method.
ContentResult Content Returns a user-defined content type.
JsonResult Json Returns a serialized JSON object.
JavaScriptResult JavaScript Returns a script that can be executed on the client.
FileResult File Returns binary output to write to the response.
EmptyResult (None) Represents a return value that is used if the action method must return a null result (void).

Examples:
public ViewResult Index()
        {
            ViewBag.CurrentDate = DateTime.Now;
            ViewData["Message"] = "Hello";
            var model = new IndexModel()
            return View(model);
        }

        public ContentResult Index(string contentType)
        {
            switch (contentType)
            {
                case "plain" :
                    return Content("This is plain text", "text/plain", Encoding.Default);
                    break;
                case "xml":
                     XElement data = new XElement("Emp", new XAttribute("firstname", e.Title), new XAttribute("lastname", e.Description));
                     return Content(data.ToString(), "text/xml");
                    break;
                default:
                    return Content("This is plain text", "text/plain", Encoding.Default);
                    break;
            }
        }

     
        public JsonResult JsonData()
        {
            var model = new IndexModel()
            return Json(model);
        }

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

        public FileStreamResult DownloadReport(){
            Stream stream = "...stream...";
            return File(stream, "text/html");
        }

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


Other Posts: MVC3 Overview | Filters




2 comments:

  1. Thanks for the useful information.. nice article
    SEO training in chennai

    ReplyDelete
  2. .Net more secure framework for web development, after development, we can take action in these as Value-type actions are compulsory. In which you can change any null able things. Value-type parameters work correctly.

    ReplyDelete