Controllers of ASP. NET MVC

Source: Internet
Author: User

The following is the definition of a controller:

    public class ProductController : Controller    {        //        // GET: /Product/        public ActionResult Index()        {            return View();        }        public ActionResult Help()        {            return View();        }        public ActionResult Details(int Id)        {            return View();        }    }

 

1. Understanding of return view () in action

That is, actionresult. Here return view () is actually to return HTML content to the page for display, while actionresult has many types:

· View ()-returns a viewresult.

· Partialview ()-returns a partialviewresult.

· Redirecttoaction ()-returns a redirecttorouteresult.

· Redirect ()-returns a redirectresult.

· Content ()-returns a contentresult.

· JSON ()-return a jsonresult.

· File ()-returns a fileresult.

· JavaScript ()-returns a javascriptresult.

· Redirecttoroute ()-returns a redirecttorouteresult.

Explanation:

· Viewresult-indicates a common ASP. net mvc view.

· Partialviewresult-indicates a piece of ASP. net mvc view.

· Redirectresult-Indicates redirecting to another controller action or URL.

return RedirectToAction("Index"); 
return RedirectToAction(“Index”, “Product”);
return RedirectToAction(“Details”, new {id=53});

 

· Contentresult-indicates to send some basic types of content to the browser. Any basic type of. Net can be string, Int, or double.

 public string SayHello()   {         return "Hello";   }

 

· Jsonresult-return a JSON type to the browser

          public ActionResult List()          {              var quotes = new List<string>              {                  "Look before you leap",                  "The early bird gets the worm",                  "All hat, no cattle"              };                            return Json(quotes);          }

 

· Fileresult-returns an object for download

        public ActionResult Download()          {                           return File("~/Content/CompanyPlans.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "CompanyPlans.docx");          }    

 

· Emptyresult-no result is returned for an action.

· Httpunauthorizedresult-returned HTTP unauthorized status code.

· Javascriptresult-returns a Javascript file.

· Redirecttorouteresult-redirect to the action of another controller using route values

 

Ii. How to control the call of an action

1. Use acceptverbs

Check the Code:

        // GET: /Employee/Create          [AcceptVerbs(HttpVerbs.Get)]          public ActionResult Create()          {              return View();          }             // POST: /Employee/Create          [AcceptVerbs(HttpVerbs.Post)]          public ActionResult Create(Employee employeeToCreate)          {              try              {                  _repository.InsertEmployee(employeeToCreate);                  return RedirectToAction("Index");              }              catch              {                  return View();              }          }            // DELETE: /Employee/Delete/1          [AcceptVerbs(HttpVerbs.Delete)]          public ActionResult Delete(int id)          {              _repository.DeleteEmployee(id);              return Json(true);          }

 

It is used to control whether to trigger the create action during get or post operations.

Supported HTTP action types:

· Options-returns information about the communication options available.

· Get-returns whatever information is identified by the request.

· Head-performs the same operation as get without returning the message body.

· Post-posts new information or updates existing information.

· Put-posts new information or updates existing information.

· Delete-deletes information.

· Trace-performs a message loop back.

· Connect-used for SSL tunneling.

 

2. Use actionname

        [ActionName("Edit")]          [AcceptVerbs(HttpVerbs.Get)]          public ActionResult Edit_GET(Merchandise merchandiseToEdit)          {              return View(merchandiseToEdit);          }

 

3. Use actionmethodselector

namespace MvcApplication1.Selectors  {      public class AjaxMethod : ActionMethodSelectorAttribute      {          public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)          {              return controllerContext.HttpContext.Request.IsAjaxRequest();          }      }  } 

 

Code in controller:

        [AjaxMethod]          [ActionName("Index")]          public string Index_AJAX()          {              var selectedIndex = _rnd.Next(_news.Count);              return _news[selectedIndex];          }
 
3. Special processing: processing of actions not defined in the request
    public class CatalogController : Controller      {                   public ActionResult Create()          {              return View();          }            public ActionResult Delete(int id)          {              return View();          }              protected override void HandleUnknownAction(string actionName)          {              ViewData["actionName"] = actionName;              View("Unknown").ExecuteResult(this.ControllerContext);          }          }

 

Handleunkonwnaction is used. By default, the Error 404 resource not found is returned. You can reload the definition.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.