路由传递参数
ASP.NET MVC 根据传入URL调用不同的控制器类()以及他们中不同的操作方法
//在HellowordController中的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyPractice.Controllers
{
public class HellowordController : Controller
{
// GET: Helloword
public string Welcome(string name, int num = 1)
{
return HttpUtility.HtmlEncode("Hello " + name + ", Your number is: " + num);
}
}
}
设置路由格式
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",//分别对应传入URL中的控制器、方法名和参数
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
可以将参数通过路由传递给控制器
在浏览器中输入URL:
http://localhost:xxx/Helloword/Welcome/1?name=Erin
呈现:
上面的name和num作为查询字符串传递,?是分隔符。
添加一个路由,将传入参数作为路由数据
routes.MapRoute(
name: "Hello",
url: "{controller}/{action}/{name}/{id}"
);
在浏览器中输入URL:
http://localhost:xxx/Helloword/Welcome/Erin/1
将呈现相同结果