MVC的路径选择十分灵活,可以用类似/parm1/parm2/parm3/ 的方式(这个有点象iis的urlrewriter),也可以象传统url那样用/?parm1=a&parm2=b&parm3=c这样访问
关键是Global.asax中Route规则的配置
以下是一个Global.asax的示例:
protected void Application_Start(object sender, EventArgs e)
{
// Note: Change Url= to Url="[controller].mvc/[action]/[id]" to enable
// automatic support on IIS6
RouteTable.Routes.Add(new Route
{
Url = "[controller]/[action]",
Defaults = new { action = "Index" },
RouteHandler = typeof(MvcRouteHandler)
});
RouteTable.Routes.Add(new Route
{
Url = "[controller]/[action]/[id]",
Defaults = new { action = "Index", id = (int?)null },
RouteHandler = typeof(MvcRouteHandler)
});
RouteTable.Routes.Add(new Route
{
Url = "[controller]/[action]/[id]/[name]",
Defaults = new { action = "Index", name = (string)null,id=(int?)null },
RouteHandler = typeof(MvcRouteHandler)
});
RouteTable.Routes.Add(new Route
{
Url = "[controller]/[action]/[id]/[name]/[sex]",
Defaults = new { action = "Index", name = (string)null, id = (int?)null,sex=(string)null },
RouteHandler = typeof(MvcRouteHandler)
});
RouteTable.Routes.Add(new Route
{
Url = "Default.aspx",
Defaults = new { controller = "Home", action = "Index", id = 2, name = "Jimmy",sex="female" },
RouteHandler = typeof(MvcRouteHandler)
});
}
对应的HomeController文件:
public class HomeController : Controller
{
/// <summary>
/// Example URL: /Home/Index/?id=2&name=abc&sex=male (对应Url = "[controller]/[action]")
/// /Home/Index/2/?name=abc&sex=male (对应Url = "[controller]/[action]/[id]")
/// /Home/Index/2/abc/?sex=male (对应Url = "[controller]/[action]/[id]/[name]")
/// /Home/Index/2/abc/male/ (对应Url = "[controller]/[action]/[id]/[name]/[sex]")
/// /Home/Index/2/abc/ (对应Url = "[controller]/[action]/[id]/[name]")
/// /Home/Index/2/ (对应Url = "[controller]/[action]/[id]")
/// </summary>
/// <param name="id"></param>
[ControllerAction]
public void Index(int? id,string name,string sex)
{
ViewData["id"] = id;
ViewData["name"] = name;
ViewData["sex"] = sex;
RenderView("Index");
}
}
对应的Index视图:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MVCDemo.Views.Home.Index" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<h2>Welcome to my ASP.NET MVC Application!</h2>
id=<%=ViewData["id"] %> <br/>
name=<%=ViewData["name"] as string %><br/>
sex=<%=ViewData["sex"] as string %>
</asp:Content>
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有