ASP. NET mvc3 series tutorial-Controller & view

Source: Internet
Author: User
Document directory
  • I: basic concepts of controllers and views
  • II: Controller
  • III: View
  • IV: source code download
I: basic concepts of controllers and views

1. Controller Concept

Controller in ASP. net mvc3 is an implementation of the final processing of client requests. It has a hard condition that system must be implemented. web. MVC. icontroller interface, and the class name must end with controller. Although it is difficult to implement an interface by yourself according to hard conditions, but fortunately it is in ASP. net mvc3 contains a default implementation. We only need to set the class name to the end of the controller and inherit the system. web. MVC. controller class, now you can easily implement the icontroller interface. if you do not like this default implementation method, but implement icontroller on your own. the following code provides a simple reference:

Using system. web. MVC; using system. web. routing; namespace mvcapplication1.controllers {public class nodefacontroller Controller: icontroller {void icontroller. execute (requestcontext) {var httpcontext = requestcontext. httpcontext; var response = httpcontext. response; response. contenttype = "text/html; charset = UTF-8"; response. write ("your own simple implementation! Hello World ");}}}

Note: The Controller class is not hard to be placed in the *. controllers namespace.

The Code is as follows:

Using system. Web. MVC; namespace mvcapplication1 {public class hellocontroller: controller {public actionresult index () {return content ("Default implementation! Hello World ");}}}

You can try it manually.

2. View Concept

The view is easy to understand. you can understand the view *. aspx or *. cshtml file. however, 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 as agreed ~ /Views/{controller}/view. cshtml.
In addition, the view also contains the viewengine. This article does not cover this advanced topic.

We can see in ~ The {controller} In/views/{controller}/view. cshtml does not need to name the folder at the end of controller like the class name.

3. Working principle diagram

Of course, the internal working principle will be much more complicated than this figure. It is just for everyone to understand it! If any error occurs, please point it out. Thank you!

Tip: mvchandler implements the ihttpasynchandler, ihttphandler, and irequiressessionstate interfaces. When I debug them, I find that they all adopt asynchronous routes. anyone who knows about this method may wish to answer this question for me!

 

II: Controller

1. Operation Method

The meaning of the operation method refers to the method that inherits the type of the return value defined in the system. Web. MVC. Controller class and can be compatible with actionresult.

Using system. web. MVC; namespace mvcapplication1.controllers {public class homecontroller: controller {// <summary> // hi, I am using the index operation method /// </Summary> /// <returns> </returns> Public actionresult index () {viewbag. message = "Welcome to ASP. net MVC! "; Return view () ;}/// <summary> // er, I am a about Operation Method /// </Summary> /// <returns> </returns> Public actionresult about () {return view ();} /// <summary> /// you can add features that are not an operation method to the method. /// </Summary> /// <returns> </returns> [nonaction] Public String nonaction () {return "sorry. I am not an operation method. Please do not call it in disorder! ";}}}

You can also use the [actionname ("RENAME operation method")] feature to rename the operation method.

[Actionname ("newactionname")] public actionresult renameaction () {return content ("use features to change the vest ");}

2. Type of the return value type of the Operation Method

Currently, ASP. NET mvc3 provides 11 actionresult implementations by default.
In the system. Web. MVC namespace
Actionresult
Contentresult
Emptyresult
Fileresult
Httpstatuscoderesult
Httpnotfoundresult
Httpunauthorizedresult
Javascriptresult
Jsonresult
Redirectresult
Redirecttorouteresult
Viewresultbase
Partialviewresult
Viewresult

Sample Code:

Using system. web. MVC; namespace mvcapplication1.controllers {public class actionresultcontroller: controller {public actionresult index () {return view ();} public actionresult contentresult () {return content ("Hi, I am contentresult result ");} public actionresult emptyresult () {// The empty result is of course blank! // If you believe it or not, I believe in return New emptyresult ();} public actionresult fileresult () {var imgpath = server. mappath ("~ /Demo.jpg "); Return file (imgpath," application/X-jpg "," demo.jpg ");} public actionresult httpnotfoundresult () {return httpnotfound ("Page not found");} public actionresult httpunauthorizedresult () {// when not verified, jump to logon return New httpunauthorizedresult ();} public actionresult implements criptresult () {string JS = "alert (\" Hi, I'm JavaScript. \ ");"; return JavaScript (JS);} public actionresult jsonresult () {Var jsonobj = new {id = 1, name = "Xiaoming", sex = "male", like = "soccer"}; return JSON (jsonobj, jsonrequestbehavior. allowget);} public actionresult redirectresult () {return redirect ("~ /Demo.jpg ");} public actionresult redirecttorouteresult () {return redirecttoroute (New {controller =" hello ", Action =" "});} public actionresult viewresult () {return view ();} public actionresult partialviewresult () {return partialview ();} // prohibit direct access to childaction [childactiononly] public actionresult childaction () {return partialview () ;}// use childaction public actionresult usingchildaction () {return view ();}}}

Note that the HTTP status code and contenttype returned by some operation methods are different during execution .~ If you want to know how many contenttype settings are available, refer

 

3. Operation Method Parameters

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

First, we need to add a new route ing, and then set three placeholder parameters, namely P1, P2, and P3. then, we will constrain P1 as a combination of letters and numbers only, the P2 constraint is only a number, and P3 does not add a constraint.

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

How to add a home Controller

Public actionresult usingparams (string P1, Int? P2, string P3) {string output = string. Empty; Output + = "p1 =" + (P1 ?? "Null"); Output + = "<br/> P2 =" + (p2.hasvalue p2.value. tostring (): "No value"); Output + = "<br/> P3 =" + (P3 ?? "Null"); Return content (output );}

Running Effect

Here, we will get a URL routing setting like Youku.

Route settings

routes.MapRoute(    "YouKu_Show",    "v_{action}/id_{id}.html",    new { controller = "YouKu" },    new { id = "[a-z0-9]{13}" },    new string[] { "MvcApplication1.YouKu" });routes.MapRoute(    "YouKu_PlayList",    "v_{action}/{id}.html",    new { controller = "YouKu" },    new { id = "[a-z0-9]{12}" },    new string[] { "MvcApplication1.YouKu" });

Detailed code will be released at the end of the article.

III: View

1. I have already written an article about view syntax for a long time. I will not mention it here.

2. How to interact data between views and controllers

In the previous contacts, we had some knowledge about controllers and views. next, we will understand several common data interaction methods between them. note: Asp. net MVC does not have ispostback. if you need to combine webform and MVC. sorry, I personally disagree with this method. the main reason for choosing MVC is that you do not want to deal with runat = Server any more. NET development without running at = server ). another point is that MVC is also convenient for testing. ~ In the past, if you want. net testing, we can imagine that if you set a preset value for each runat = server control that needs to be tested, the complexity of the attribute is quite high. in addition, all problems cannot be found at the root. ~ Maybe my testing ASP. net conjecture is not true at all. during the test, you often need to build each time, and then test and check the buttons one by one on the pages to be tested .. OK. I will not mention these concerns. the following describes several data interaction methods in MVC.

2.1 ASP. net mvc does not have ispostback. How do I implement get and post processing?
First, I post a simple code to show you how to process get and post in ASP. NET mvc3.

// By default, GET requests are processed. Of course, you can also explicitly add [httpget] public actionresult usingviewbag () {return view ();} // explicitly set the operation method to process the POST request [httppost] public actionresult usingviewbag (string input) {If (string. isnullorwhitespace (input) {viewbag. MSG = inputblank;} else {viewbag. MSG = "you entered:" + input;} return view ();}

In ASP. net mvc, you can use the [http *] or [acceptverbs (httpverbs. *)] feature to implement ispostback similar to webform.

2.2 Data Interaction modes of ASP. NET mvc3

A: ASP. NET native request, response.

Members of system. Web. MVC. Controller: httpcontext, request, response, session, and user are similar to those in webform.

Request. querystring, request. Form, request. Cookies, routedata. Values, etc.

B: viewdata, viewbag, and tempdata of ASP. NET mvc3

Using system. web. MVC; namespace mvcapplication1.controllers {public class paramscontroller: controller {string inputblank = "you entered blank"; Public actionresult index () {return view ();} // by default, GET requests are processed. Of course, you can also explicitly add [httpget] public actionresult usingviewbag () {return view ();} // explicitly set the operation method to process the POST request [httppost] public actionresult usingviewbag (string input) {If (string. isnullorwhitespace (input) {viewbag. MSG = inputblank;} else {viewbag. MSG = "you entered:" + input;} return view ();} public actionresult usingviewdata () {return view ();} [httppost] public actionresult usingviewdata (string input) {If (string. isnullorwhitespace (input) {viewdata ["MSG"] = inputblank;} else {viewdata ["MSG"] = "you entered:" + input ;} return view ();} public actionresult usingtempdata () {return view ();} [httppost] public actionresult usingtempdata (string input) {If (string. isnullorwhitespace (input) {tempdata ["MSG"] = inputblank;} else {tempdata ["MSG"] = "you entered:" + input ;} return view ();}}}

For a more detailed discussion, I may have to write another article. Next I will write a model, and I will write another article about the @ HTML extension method.

IV: source code download


Download source code
End .... Thanks!

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.