Go ASP. NET MVC 5-Controller

Source: Internet
Author: User

MVC represents: model - view - controller . MVC is a well-architected and easy-to-test and maintainable development model. Applications based on the MVC pattern include:

· Models: Data class that represents the data for the application and uses validation logic to enforce the business rules.

· Views: The template file used by the application to dynamically generate HTML.

· Controllers: Process the browser request, obtain the data model, and then specify the view template to respond to the browser request.

In this series of tutorials, we'll cover all of these concepts and show you how to use them in ASP. NET MVC 5 to build your application.

First, let's create a controller class. In Solution Explorer , right-click the Controller folder (Controllers ), and then select Add Controller.

In the Add Scaffold dialog box, click MVC5 Controller - empty , and then click Add .

Name the new controller as "Helloworldcontroller" and click "Add".

Note that a new file named HelloWorldController.cs and a new folder Views\helloworldare created in Solution Explorer . The file will be opened by default by the IDE.

Replace the contents of the file with the following code.

Using System.Web; Using SYSTEM.WEB.MVC; namespace Mvcmovie.controllers {public     class Helloworldcontroller:controller     {////         GET:/ helloworld/public         string Index ()         {             return ' This is my <b>default</b> action ... ';         }         //GET:/helloworld/welcome/public          string Welcome ()         {             Return ' This is the Welcome action method ...";         }     } }

In this example, the Controller method returns the HTML of a string. The first method in the named Helloworldcontroller code of this controller is named index. Let's call it from the browser. Run the application (press F5 or CTRL + F5). Enter the path "HelloWorld" in the address bar of the browser. (for example, in the following example: Http://localhost:1234/HelloWorld) the page behaves as follows in the browser. In the method above, the code returns a string directly. You tell the system to return only some HTML, and the system does!

ASP. NET MVC calls different controller classes (and their internal different action methods) depending on the incoming URL. The default URL routing logic for ASP. NET MVC uses this format to determine which code to invoke:

/[controller]/[actionname]/[parameters]

You can also resolve rules by configuring URL routing within the app_start/routeconfig.cs file:

public static void RegisterRoutes (RouteCollection routes) {    routes. Ignoreroute ("{resource}.axd/{*pathinfo}");    Routes. MapRoute (        name: "Default",        URL: "{controller}/{action}/{id}",        defaults:new {controller = "Home", action = "Index", id = urlparameter.optional});

If you run the application and do not provide any URL segments, the default is "Home" for the controller and the "Index" action method, specified in the Defaults section of the preceding code:

    • The first part of the URL determines which controller class will be executed. So /helloworld maps to the Helloworldcontroller controller class.
    • The second part of the URL determines which operation method to execute in the controller class. Therefore, /helloworld/indexwill cause HelloWorldController the Controller class's index method to be executed. Note that we only need to browse the /helloworld path and the index method is called by default. If no explicit action method is specified, the index method is called by the Controller class by default.
    • The third part of the URL segment (parameters parameter) is the routing data. In this tutorial, we'll see the routing data later.

Browse Http://localhost:xxxx/HelloWorld/Welcome. the Welcome method is run and returns the string: "This is the Welcome action method ...". The default MVC map is/[controller]/[actionname]/[parameters] for this URL, the controller class is HelloWorld and the action method is welcome, and you have not used the [Parameters] part of the URL.

Let's change this example a little bit so that you can use the URL to pass some parameter information to the controller class (for example, /helloworld/welcome?name=scott&numtimes=4). Change your welcome method to include two parameters, as shown below. It is important to note that the sample code uses the optional parameters feature of the C # language, and the Numtimes parameter has a default value of 1 when the value is not passed.

public string Welcome (string name, int numtimes = 1) {      

Security Note: The above code uses HttpServerUtility.HtmlEncode to protect the application from the malacious input (that is, JavaScript). For more information, see how to:protect against Script exploits in a WEB application by applying HTML Encoding to Strings.

Run your application and browse for this URL (http://localhost:xxxx/HelloWorld/Welcome?name=Scott&numtimes=4). You can try different values for the parameter name and Numtimes. The ASP. NET MVC Model binding system automatically maps the query string in the URL in the address bar to the parameters in your method.

The above example does not use the part of the URL segment parameter (Parameters). Pass the parameters for name and numtimes through query strings.

Replace the "Welcome" method with the following code:

public string Welcome (string name, int id = 1) {     return Httputility.htmlencode ("Hello" + name + ", ID:" + ID);}

Run the application and enter the following URL: http://localhost:xxx/HelloWorld/Welcome/3?name=Rick

The parameters of the third part of the URL match the parameter ID.

By looking at the following registerroutes routing rule function:

public static void RegisterRoutes (RouteCollection routes) {     routes. Ignoreroute ("{resource}.axd/{*pathinfo}");     Routes. MapRoute (         name: "Default",         URL: "{controller}/{action}/{id}",         defaults:new {controller = "Home", action = "Index", id = urlparameter.optional}     ); }

In an ASP. NET MVC application, routing data is passed through parameters as a more typical application (as with the ID parameter passed with query string above). You can also add a route to pass the name and Numtimes parameters in the URL of the route data. In the app_start\routeconfig.cs file, add a route for "Hello":

public class routeconfig{public    static void RegisterRoutes (RouteCollection routes)    {       routes. Ignoreroute ("{resource}.axd/{*pathinfo}");       Routes. MapRoute (           name: "Default",           URL: "{controller}/{action}/{id}",           defaults:new {controller = "Home", action = "Index", id = urlparameter.optional}       );       Routes. MapRoute (            name: "Hello",            URL: "{controller}/{action}/{name}/{id}"        );}    }

Using the application, in the browser input:/LOCALHOST:XXX/HELLOWORLD/WELCOME/SCOTT/3.

The default routing for many MVC applications will work correctly. You'll learn later in this tutorial by using model-bound data, and you don't have to modify the default route.

In the example above, the controller has been doing the functions of the "VC" part of MVC: that is, the work of the view and the controller. The controller returns HTML content directly. Typically, you will not let the controller return HTML directly, because the code becomes cumbersome. Instead, we typically use a separate view template file to help generate the returned HTML. Let's take a look at how we can do that.

Controller is an important part of MVC, with the knowledge of this section of learning, I believe you will be more in-depth understanding of MVC. So in the MVC development process, in addition to the above knowledge, what other tools can be used? ComponentOne Studio ASP is a control package for the MVC platform that integrates seamlessly with Visual Studio and is fully compatible with MVC6 and ASP. NET 5.0, which will significantly increase productivity.

-----------------------------------------------------------------------------------------

The 12 articles in the ASP. NET MVC 5 Getting Started Guide are summarized below:

1. asp 5-Start MVC 5 Tour

2. ASP. NET MVC 5-Controller

3. ASP. NET MVC 5-View

4. asp 5-pass data from the controller to the view

5. ASP. 5-Add a model

6. asp 5-Create a connection string (Connection string) and use SQL Server LocalDB

7. ASP. 5-access the data model from the controller

8. ASP. 5-Validation editing method and edit view

9. asp 5-Add new fields to movie tables and models

ASP. NET MVC 5-Add a validator to the data model

ASP. NET MVC 5-query details and Delete methods

ASP. NET MVC 5-Create an app with the Wijmo MVC 5 template for 1 minutes

Go ASP. NET MVC 5-Controller

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.