MVC music store-Part 2: Controller

Source: Internet
Author: User

First, let's take a picture to learn the working principle of MVC in advance.

 

In traditional Web frameworks, the imported URLs are usually directly mapped to the corresponding files on the disk. For example,Products. Aspx"Or"/Products. PhpThe URL may be composed ofProducts. Aspx "or"/Products. Php file to process.

 

In the web-based MVC Architecture, URL ing to the server is different. Unlike the traditional Web framework, they map URLs to files on disks, but to methods in the class. The ing to files is replaced with methods mapped to classes. These classes are called"Controllers"(Controller ). These classes are responsible for processing incoming HTTP requests, user input, retrieval and storage of data, and are sure to return the response to the client (display HTML, download file Redirection URL, etc ).

 

Add homecontroller

Now add a controller to start our MVC music store, which will process the URL linked to the home page. We follow the default ASP. net mvc Naming Convention (introduced in the previous article). The new class is named as follows:Homecontroller.

 

Find"Controllers"Folder, right-click, and select" Add-> controller ":

 

This opens the "add controller" dialog box. Change the name to"Homecontroller", And then press" add.

 

This will create a new file,Homecontroller. CS will generate the followingCode:

 Using  System;  Using  System. Collections. Generic;  Using  System. LINQ;  Using  System. Web;  Using  System. Web. MVC;  Namespace  Mvcmusicstore. controllers { Public   Class  Homecontroller: controller {  //          //  Get:/home/          Public  Actionresult index (){  Return  View ();}}} 

Try to use a simple return string to replace the original index method. You only need to modify the following two places:

    • Change the return type of the method from actionresult to string.
    • Modify the Return Statement and return the string "Hello MVC !"

The modified method is as follows:

Public StringIndex (){Return "Hello MVC!";}

RunProgram

Now let's run the site, press F5 (debugging started) or crtl + F5 (not debugging started), and then open a new browser page automatically, as shown below:

 

We quickly created a new web site, added three lines of code, and displayed a line of text in the browser. This is just the beginning.

Note: after the program runs, a random port number is generated. The site runs at http: // localhost: 6886/, so it is using the port number 6886.

 

Add storecontroller

Previously, we have added a simple homecontroller to implement the home page of the website. Now, let's add another controller to implement the MVC music store browsing function. The following three functions are required:

    • Music category list
    • Albums in the category list
    • Album details

Perform the same operations as adding the homecontroller controller above to add the stroecontroller. The newly added stroecontroller. the index method already exists in CS. We use the index method to implement the list page of all categories, we will also add two methods to implement the other two functions (album and album information in the category list ).

 

These methods () are called "Controller actions" in our controller and are used together with the previous homecontroller. like the index () method, they work to respond to URL requests and determine which content should be sent back to the browser or the URL requested by the user.

 

We modified the index method and asked him to return the string "Hello MVC store. index () ", followed by the two methods (Browse (), details (), also use this requirement to complete the implementation of stroecontrolle.

 Using  System;  Using  System. Collections. Generic;  Using  System. LINQ;  Using  System. Web; Using  System. Web. MVC;  Namespace  Mvcmusicstore. controllers {  Public   Class  Storecontroller: controller {  //          //  Get:/store/          Public   String  Index (){  Return   " Hello MVC store. Index ()  "  ;}  Public   String Browse ( String  Genre ){  Return   "  Hello MVC store. Browse ()  "  ;}  Public   String Details ( Int ID ){  Return   "  Hello MVC store. Details ()  "  ;}}} 

Run the project again and browse the following URLs

    • /Store
    • /Store/browse
    • /Store/details

Accessing these URLs will call the action methods in the Controller and return a string:

 

However, these are just some unchanged strings. Now, let's change them to dynamic ones and get some information from the URL and input it to the page. First, we will modify the Browse method. We will add a parameter-gener for this method. When browse () is called, Asp. net MVC will automatically pass a "gener" parameter.

////Get:/store/browse? Genre = discoPublic StringBrowse (StringGenre ){StringMessage = httputility. htmlencode ("Store. Browse, genre ="+Genre );ReturnMessage ;}

Note: We use the httputility. htmlencode method to determine user input.This prevents users from using similar

/Store/browse? Genre = <SCRIPT> window. Location = 'HTTP: // hackersite.com '</SCRIPT>Such links are used to inject attacks into websites. Now let's take a look at the results.

 

What we will do next is to let details () read and display an input parameter named "ID. Unlike the Browse () method, I do not use the id value as the query string, but use it as part of the URL, for example:/Store/details/5. ASP. net MVC is easy to implement the idea just now, and we don't need to configure anything, Asp. net MVC default routing is to regard the action part in the URL as a parameter named "ID. If there is a parameter named "ID" in the operation method, ASP. net mvc will automatically pass as a parameter.

////Get:/store/details/5Public StringDetails (IntID ){StringMessage ="Store. Details, id ="+ID;ReturnMessage ;}

Run the program, browse/store/details/5

 

Now let's review what we have done:

    • Create an ASP. net mvc 3 Project in vs2010
    • Discussed the default directory (Convention) of ASP. net mvc 3 applications)
    • I learned how to use the web site running in the ASP. NET development server (you can learn about the ports generated when the programs run on the Internet)
    • Two Controller classes are created: homecontroller and stroecontroller.
    • Three methods are added to the Controller to respond to the URL request and return the result to the browser.

 

Experience: The second part focuses on how to add a new controller to a new project and access the corresponding methods in the Controller in the browser.

1. Create a new controller. By default, there is a method to return to the view. In this article, replace it with a string. After the program runs, the string is displayed in the browser;

2. the method name convention in the Controller: only the method name is asked, regardless of the parameter and return value of the method (as can be seen from 1, the default index method is to return the view, but we change it to return the string, );

3. controller parameters: There are three methods (index/Browse/details) in the stroecontroller. Different parameter passing methods are displayed. The specific cause is in the method. When the string is returned, the Browse () method usesHttputility. htmlencode to prevent JS injection attacks.

Each articleArticleI have written all of the following content: controller,Action and parameters are three parts of the website URL. If you do not enter the Controller name in the address bar, homecontroller is used by default. If no method name is provided, the index method is used by default. There are two types of parameters. When the accepted parameter is a string, httputility. htmlencode should be used to prevent JS injection attacks.

 

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.