MVC stands for model-view-controller.  MVC is a pattern for developing applications that are well architected, testable  and easy to maintain. MVC-based applications contain:

  • Models: Classes that represent the data of the application  and that use validation logic to enforce business rules for that data.
  • Views: Template files that your application uses to dynamically  generate HTML responses.
  • Controllers: Classes that handle incoming browser requests,  retrieve model data, and then specify view templates that return a response  to the browser.

We'll be covering all these concepts in this tutorial series and show you how  to use them to build an application.

Let's begin by creating a controller class. In Solution  Explorer, right-click the Controllers folder  and then click Add,  then Controller.

In the Add Scaffold dialog box, click MVC 5  Controller - Empty, and then click Add.

Name your new controller "HelloWorldController" and click Add.

Notice in Solution  Explorer that a new file  has been created named HelloWorldController.cs and a new folder Views\HelloWorld. The controller is open in 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..."; 
        } 
    } 
}

The controller methods will return a string of HTML as an example. The controller is named HelloWorldController and  the first method is named Index.  Let’s invoke it from a browser. Run the application (press F5 or Ctrl+F5). In the  browser, append "HelloWorld" to the path in the address bar. (For example,  in the illustration below, it's http://localhost:1234/HelloWorld.)  The page in the browser will look like the following screenshot. In the method above, the code returned a string directly. You told the system to just return some HTML, and it did!

ASP.NET MVC invokes different controller classes (and different action methods within  them) depending on the incoming URL. The default URL routing logic used by ASP.NET  MVC uses a format like this to determine what code to invoke:

/[Controller]/[ActionName]/[Parameters]

You set the format for routing in 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 }
    );
}

When you run the application and don't supply any URL segments, it defaults to  the "Home" controller and the "Index" action method specified in the defaults  section of the code above.

The first part of the URL determines the controller class to execute. So /HelloWorld maps  to the HelloWorldController class.  The second part of the URL determines the action method on the class to execute.  So /HelloWorld/Index would  cause the Index method of the HelloWorldController class to execute. Notice that we only had to browse to /HelloWorld and  the Index method  was used by default. This is because a method named Index is the default method that will be called on a controller if one is not explicitly specified. The third part of the URL segment ( Parameters) is for route data. We'll see route data later on in this  tutorial.

Browse to http://localhost:xxxx/HelloWorld/Welcome.  The Welcome method  runs and returns the string "This is the Welcome action method...". The  default MVC mapping is /[Controller]/[ActionName]/[Parameters].  For this URL, the controller is HelloWorld and Welcome is  the action method. You haven't used the [Parameters] part  of the URL yet.

Let's modify the example slightly so that you can pass some parameter information  from the URL to the controller (for example, /HelloWorld/Welcome?name=Scott&numtimes=4).  Change your Welcome method  to include two parameters as shown below. Note that the code uses the C# optional-parameter feature to indicate that the numTimes parameter should default to 1 if no value is passed for that parameter.

public string Welcome(string name, int numTimes = 1) {
     return HttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " + numTimes);
}
Security Note: The code above uses HttpServerUtility.HtmlEncode to protect the application from malicious input (namely 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 to the example URL (http://localhost:xxxx/HelloWorld/Welcome?name=Scott&numtimes=4).  You can try different values for name and numtimes in  the URL. The ASP.NET MVC model binding system automatically maps the named parameters from  the query string in the address bar to parameters in your method.

In the sample above, the URL segment ( Parameters) is not used, the name and numTimes parameters are passed as query strings. The ? (question mark) in the above URL is a separator, and the query strings follow. The & character separates 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

This time the third URL segment  matched the route parameter ID. The Welcome action method contains a parameter  (ID) that matched the URL specification in the RegisterRoutes method.

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 ASP.NET MVC applications, it's more typical to pass in parameters as route  data (like we did with ID above) than passing them as query strings. You could also  add a route to pass both the name and numtimes in  parameters as route data in the URL. In theApp_Start\RouteConfig.cs  file, add the "Hello" route:

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}"
       );
   }
}

Run the application and browse to /localhost:XXX/HelloWorld/Welcome/Scott/3.

For many MVC applications, the default route works fine. You'll learn later in this tutorial to pass data using the model binder, and you won't have to  modify the default route for that.

In these examples the controller has been doing the "VC" portion  of MVC — that is, the view and controller work. The controller is returning HTML  directly. Ordinarily you don't want controllers returning HTML directly, since  that becomes very cumbersome to code. Instead we'll typically use a separate  view template file to help generate the HTML response. Let's look next at how  we can do this.

2.Adding a Controller的更多相关文章

  1. 006.Adding a controller to a ASP.NET Core MVC app with Visual Studio -- 【在asp.net core mvc 中添加一个控制器】

    Adding a controller to a ASP.NET Core MVC app with Visual Studio 在asp.net core mvc 中添加一个控制器 2017-2-2 ...

  2. Adding a Controller

    MVC stands for Model, View, Controller. MVC is a pattern for developing applications such that each ...

  3. ASP.NET Core 中文文档 第二章 指南(4.2)添加 Controller

    原文:Adding a controller 翻译:娄宇(Lyrics) 校对:刘怡(AlexLEWIS).何镇汐.夏申斌.孟帅洋(书缘) Model-View-Controller (MVC) 架构 ...

  4. @Controller和@RestController的区别

    1. Controller, RestController的共同点 都是用来表示spring某个类的是否可以接收HTTP请求 2.  Controller, RestController的不同点 @C ...

  5. Spring中@Controller和@RestController之间的区别

    1. Controller, RestController的共同点 都是用来表示Spring某个类的是否可以接收HTTP请求 2.  Controller, RestController的不同点 @C ...

  6. @Controller和@RestController之间的区别

    1. Controller, RestController的共同点 都是用来表示Spring某个类的是否可以接收HTTP请求 2. Controller, RestController的不同点 @Co ...

  7. 【spring Boot】Spring中@Controller和@RestController之间的区别

    spring Boot入手的第一天,看到例子中的@RestController ............. 相同点:都是用来表示Spring某个类的是否可以接收HTTP请求 不同点:@Controll ...

  8. Getting Started with ASP.NET Web API 2 (C#)

    By Mike Wasson|last updated May 28, 2015 7556 of 8454 people found this helpful Print   Download Com ...

  9. 【ASP.NET Identity系列教程(一)】ASP.NET Identity入门

    注:本文是[ASP.NET Identity系列教程]的第一篇.本系列教程详细.完整.深入地介绍了微软的ASP.NET Identity技术,描述了如何运用ASP.NET Identity实现应用程序 ...

随机推荐

  1. 实例介绍Cocos2d-x中Box2D物理引擎:碰撞检测

    在Box2D中碰撞事件通过实现b2ContactListener类函数实现,b2ContactListener是Box2D提供的抽象类,它的抽象函数:virtual void BeginContact ...

  2. SwithAndActivity 选择开关和活动指示

    ////  ViewController.m//  SwithAndActivity////  Created by qianfeng on 15/9/21.//  Copyright (c) 201 ...

  3. css3学习笔记之2D转换

    translate() 方法 translate()方法,根据左(X轴)和顶部(Y轴)位置给定的参数,从当前元素位置移动. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...

  4. main与进程 线程

    你起一个CS游戏,这上CS游戏在操作系统中就是一个进程. 但是这个游戏一边在打枪,一边人在走动,一边还有音乐 ,打枪 , 走动 , 音乐 等都是一些线程. 线程不是由进程决定了. 也就是说:你在操作系 ...

  5. mysql 恢复备份时出错 Unknown command ‘\”

    今天恢复mysql备份时,出现了Unknown command ‘\”这样的错误,原以为是备份文件出错,重新备份导入时还是出错.研究了一凡是因为编码的问题,解决方案如下: 使用你导出备份时的编码重新导 ...

  6. Poj 3117 World Cup

    1.Link: http://poj.org/problem?id=3117 2.Content: World Cup Time Limit: 1000MS   Memory Limit: 65536 ...

  7. 2014-10 u-boot make xxx_defconfig 过程分析

    /** ****************************************************************************** * @author    Maox ...

  8. Qt5中使用lambda表达式

    c11新特性中加入了lambda表达式,所以Qt 也支持 需在.pro文件中加入 CONFIG += c++11 例子: QString program = "C:/Windows/Syst ...

  9. soinn

    Growing Cell Structures A Self-Organizing Network for Unsupervised and Supervised Learning Here, and ...

  10. 百度地图API实现多区域标记

    最近遇到一个业务就是需要需要在地图上标记多个区域.一般餐饮业做外卖的,配送范围一般是多区域的,那么在地图上标记配送范围的时候就需要能标记多个区域.长话短说,最初的实现原型的截图如下: