演练2-3:控制器的简单练习

原文出处:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller

1.新建一个默认ASP.NET MVC 4 项目

2.添加一个HelloWorld控制器,选择“空的MVC控制器”

3.编写HelloWorld控制器代码,如下。

 1     public class HelloWorldController : Controller 
 2     { 
 3         // 
 4         // GET: /HelloWorld/ 
 5  
 6         public string Index() 
 7         { 
 8             return "This is my <b>default</b> action..."; 
 9         } 
10  
11         // 
12         // GET: /HelloWorld/Welcome/ 
13  
14         public string Welcome() 
15         { 
16             return "This is the Welcome action method..."; 
17         } 
18     } 

    Index()方法的返回类型为string,而不是ActionResult。

    默认的URL路由使用格式为:/[Controller]/[ActionName]/[Parameters],所以“/HelloWorld/Index”与之相对应,调用HelloWorld控制器的Index方法。使用“/HelloWorld”效果相同,因为默认的ActionName是“Index”。

4.运行程序

 5.修改代码,了解Parameter参数

    将Welcome()方法的代码,修改如下。

1 public string Welcome(string name, int numTimes = 1) {
2      return HttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " + numTimes);
3 }

    name和numTimes用来接收路由中的值,numTimes默认为1。运行程序,输入地址为“http://localhost:xxxx/HelloWorld/Welcome?name=Scott&numtimes=4”。

原文地址:https://www.cnblogs.com/meetyy/p/3972701.html