Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Controller and View in ASP.NET MVC 3

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is to share with you about how to understand the controller and view in ASP.NET MVC 3. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

I: basic concepts of controllers and views

1. The concept of controller

The controller is an implementation that finally handles client requests in ASP.NET MVC3. It has a rigid condition that it must implement the System.Web.Mvc.IController interface, and the class naming must end with Controller. Although it is difficult to implement an interface on its own according to hard conditions, fortunately, a default implementation is included within ASP.NET MVC3. We just need to set the class naming to the end of Controller and inherit the System.Web.Mvc.Controller class, and we can easily implement the IController interface immediately. If you don't like the default implementation, you implement IController yourself. The following code serves as a simple reference:

UsingSystem.Web.Mvc; usingSystem.Web.Routing; namespaceMvcApplication1.Controllers {publicclassNoDefaultController: IController {voidIController.Execute (RequestContextrequestContext) {varhttpContext = requestContext.HttpContext; varresponse = httpContext.Response; response.ContentType = "text/html; charset=utf-8"; response.Write ("your own simple implementation! Hello World");}

Please note that the controller class is not required to be placed in the * .controllers namespace

If it is implemented using the inherited default class, the code is as follows:

UsingSystem.Web.Mvc; namespaceMvcApplication1 {publicclassHelloController: Controller {publicActionResultIndex () {returnContent ("default implementation! Hello World");}

I won't post the effect picture. You can try it manually.

two。 The concept of view

The understanding of the view is relatively simple. You can think of the view as a file of * .aspx or * .cshtml. But not all aspx and cshtml files can be used as views. They must belong to a folder named after the controller and be stored in the path ~ / Views/ {controller} / View.cshtml according to the convention.

In addition, the view also includes parsing his ViewEngine (View engine), this article does not cover this advanced topic.

We can see that {controller} in ~ / Views/ {controller} / View.cshtml does not need to end with Controller as a class name.

3. Working schematic diagram

Of course, the internal working principle will be much more complicated than this diagram. Here is just to let everyone have an understanding! Please point out if there are any mistakes. Thank you!

Tip: MvcHandler implements three interfaces: IHttpAsyncHandler, IHttpHandler and IRequiresSessionState. When I entered Debug, I found that they were all asynchronous. For this treatment, people who know it hope they can answer it for me!

II: controller

1. Operation method

An operation method refers to a method that inherits the return value defined in the System.Web.Mvc.Controller class and is compatible with ActionResult.

UsingSystem.Web.Mvc; namespaceMvcApplication1.Controllers {publicclassHomeController: Controller {/ Hi, I am the Index operation method / publicActionResultIndex () {ViewBag.Message = "Welcome to ASP.NET MVC!"; returnView ();} / er, I am the About operation method / publicActionResultAbout () {returnView () } / you can add features that are not operating methods to the method / [NonAction] publicstringNonAction () {return "dear, I'm sorry. I am not a method of operation. Oh, please don't call it randomly. ";} you can also use the [ActionName (" rename operation method ")] feature to rename the operation method. [ActionName ("NewActionName")] publicActionResultRenameAction () {returnContent ("changing a vest with features");}

two。 The type of return value type of the operation method

At present, ASP.NET MVC3 provides 11 implementations of ActionResult by default.

In the System.Web.Mvc namespace

ActionResult

ContentResult

EmptyResult

FileResult

HttpStatusCodeResult

HttpNotFoundResult

HttpUnauthorizedResult

JavaScriptResult

JsonResult

RedirectResult

RedirectToRouteResult

ViewResultBase

PartialViewResult

ViewResult

Code example:

UsingSystem.Web.Mvc; namespaceMvcApplication1.Controllers {publicclassActionResultController: Controller {publicActionResultIndex () {returnView ();} publicActionResultContentResult () {returnContent ("Hi, I am the ContentResult result");} publicActionResultEmptyResult () {/ / empty result is of course blank! / / as to whether you believe it or not, I believe returnnewEmptyResult ();} publicActionResultFileResult () {varimgPath = Server.MapPath ("~ / demo.jpg") ReturnFile (imgPath, "application/x-jpg", "demo.jpg");} publicActionResultHttpNotFoundResult () {returnHttpNotFound ("Page NotFound");} publicActionResultHttpUnauthorizedResult () {/ / if not verified, jump to Logon returnnewHttpUnauthorizedResult ();} publicActionResultJavaScriptResult () {stringjs = "alert (\" Hi, Isimm JavaScript.\ "); returnJavaScript (js) } publicActionResultJsonResult () {varjsonObj = new {Id = 1, Name = "Xiao Ming", Sex = "male", Like = "football"}; returnJson (jsonObj, JsonRequestBehavior.AllowGet);} publicActionResultRedirectResult () {returnRedirect ("~ / demo.jpg");} publicActionResultRedirectToRouteResult () {returnRedirectToRoute (new {controller = "Hello", action = ""});} publicActionResultViewResult () {returnView ();} publicActionResultPartialViewResult () {returnPartialView () } / / prohibit direct access to ChildAction [ChildActionOnly] publicActionResultChildAction () {returnPartialView ();} / / correctly use ChildAction publicActionResultUsingChildAction () {returnView ();}

Please note that when individual operation methods are executed, they return different HTTP status codes and ContentType. ~ in addition, if you want to know how many settings ContentType has, you can refer to it.

3. Parameters of the operation method

In this section, I will only demonstrate how to map URL parameters to the parameters of the operation method. For more complex uses, I will leave it to the chapter of the model.

First, we need to add a new route map, and then set three placeholder parameters, which are p1, p2, and p3. Then p1 is constrained to a combination of letters and numbers, p2 is constrained to numbers only, and p3 is not constrained.

Routes.MapRoute ("UsingParams", "p / {p1} / {p2} / {p3}", new {controller = "Home", action = "UsingParams"}, new {p1 = "[a-z0-9] +", p2 = @ "d +"})

The operation method of adding a Home controller

PublicActionResultUsingParams (stringp1, intp2, stringp3) {stringoutput = string.Empty; output + = "p1 =" + (p1?? "null"); output + = "p2 =" + (p2.HasValue p2.Value.ToString (): "No value"); output + = "p3 =" + (p3?? "null"); returnContent (output);}

Running effect

We are working on a URL routing setting that mimics YouKu.

Routing Settin

Routes.MapRoute ("YouKu_Show", "v _ {action} / id_ {id} .html", new {controller = "YouKu"}, new {id = "[a-z0-9] {13}"}, newstring [] {"MvcApplication1.YouKu"}) Routes.MapRoute ("YouKu_PlayList", "v _ {action} / {id} .html", new {controller = "YouKu"}, new {id = "[a-z0-9] {12}"}, newstring [] {"MvcApplication1.YouKu"})

The detailed code will be released at the end of the article.

III: view

1. I have written an article about the syntax of views a long time ago. I will skip it here.

two。 How to exchange data between view and controller

In the previous contact, we already have some understanding of the controller and view. Next, we will learn about several common ways of data interaction between them. Note: there is no IsPostBack in ASP.NET MVC. If you need to combine WebForm with MVC. Then I'm sorry, but I personally am very opposed to this approach. Because the main reason for choosing MVC is that you don't want to deal with runat=server anymore (of course, it's possible if you develop with ASP.NET instead of runat=server). Another point MVC is also convenient for testing. ~ in the past, if you wanted to test ASP.NET, we could imagine setting a default value for each server control of runat=server that needs to be tested, because of the many properties, the complexity can be imagined. In addition, there is no guarantee that all problems can be found at the root. ~ maybe my conjecture of testing ASP.NET is not true at all. When testing, you often need to Builder once, and then test the pages that need to be tested to check what buttons. OK, these sad things are no longer mentioned. The following describes the ways of data exchange under MVC.

2.1 ASP.NET MVC no longer has IsPostBack, how to deal with GET,POST?

First of all, I'll post a simple piece of code to show you how to deal with GET and POST under ASP.NET MVC3.

/ / Get requests are handled by default, of course, you can also explicitly add [HttpGet] publicActionResultUsingViewBag () {returnView ();} / / explicitly set the operation method to handle Post requests [HttpPost] publicActionResultUsingViewBag (stringinput) {if (string.IsNullOrWhiteSpace (input)) {ViewBag.Msg = inputBlank;} else {ViewBag.Msg = "you typed:" + input;} returnView ();}

Here you will find that under ASP.NET MVC, you use the [Http*] or [AcceptVerbs (HttpVerbs.*)] feature to implement IsPostBack similar to that under WebForm.

2.2 types of data interaction in ASP.NET MVC3

A:ASP.NET native Request,Response.

Members of System.Web.Mvc.Controller: HttpContext, Request, Response, Session, User are all similar to those under WebForm.

Request.QueryString,Request.Form,Request.Cookies,RouteData.Values et al.

ViewData,ViewBag,TempData that comes with B:ASP.NET MVC3

UsingSystem.Web.Mvc; namespaceMvcApplication1.Controllers {publicclassParamsController: Controller {stringinputBlank = "you entered a blank"; publicActionResultIndex () {returnView ();} / / handles Get requests by default, of course, you can also explicitly add [HttpGet] publicActionResultUsingViewBag () {returnView ();} / / explicitly set the operation method to handle Post requests [HttpPost] publicActionResultUsingViewBag (stringinput) {if (string.IsNullOrWhiteSpace (input)) {ViewBag.Msg = inputBlank } else {ViewBag.Msg = "you entered:" + input;} returnView ();} publicActionResultUsingViewData () {returnView ();} [HttpPost] publicActionResultUsingViewData (stringinput) {if (string.IsNullOrWhiteSpace (input)) {ViewData ["msg"] = inputBlank;} else {ViewData ["msg"] = "you entered:" + input;} returnView ();} publicActionResultUsingTempData () {returnView () } [HttpPost] publicActionResultUsingTempData (stringinput) {if (string.IsNullOrWhiteSpace (input)) {TempData ["msg"] = inputBlank;} else {TempData ["msg"] = "you typed:" + input;} returnView ();}

For a more detailed discussion, we may have to write another article. The next article is about Model, and I'm going to write another article about the extension of @ Html.

IV: source code download

The above is how to understand the controller and view in ASP.NET MVC 3. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report