url相关

当mvc程序启动的时候会主动调用Global.asax文件中的Application_Start方法,在该方法中又会主动调用静态方法RouteConfig.RegisterRoutes,这个时候会将URL和路由规则逐一进行匹配。

//使用routes.MapRoute 方法注册路由
routes.MapRoute("MyRoute", "{controller}/{action}");

//创建默认的路由规则
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

//使用静态变量的 Url片段(匹配:http://localhost:20234/xxx/Home/Index)
routes.MapRoute("", "xxx/{controller}/{action}", new { controller = "Home", action = "Index" });

//使用静态片段和默认值为特定的路由创建别名
routes.MapRoute("ShopSchema", "shop/{action}", new { controller = "Home"});//这里用户在url中输入shop,然后会被替换成Home。
routes.MapRoute("ShopSchema", "oldController/oldAction", new { controller = "Home",action="Index"});

//在控制器的方法中,接收Url中的参数
public ActionReulst CustomVariable(){
ViewBag.variable=RouteData.Values["id"];//获取Url中,id片段的值
return View();
}

 

在mvc中,使用jquery ajax请求控制器。

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>CustomVariable</title>
</head>
<body>
    <div>
        The controller is: @ViewBag.Controller
    </div>
    <div>
        The action is: @ViewBag.Action
    </div>
    <div>
        The variable is @ViewBag.CustomVariable
    </div>


    <input type="button" id="btn" name="name" value="按钮" />
</body>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(function () {
        $("#btn").click(function () {
            $.ajax({
                type: "post",
                url: "../GetData",
                data: { "name": "vichin", "age": "26", "sex": "" },
                success: function (result) {
                    alert(result);
                }
            });
        });
    });
</script>
</html>
前台代码CustomVariable.cshtml

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace UrlsAndRoutes.Controllers
{
    public class HomeController : Controller
    {        
        public ActionResult CustomVariable(string id)
        {
            ViewBag.Controller = "Home";
            ViewBag.Action = "CustomVariable";
            //ViewBag.CustomVariable = RouteData.Values["id"];
            ViewBag.CustomVariable = id;
            return View();
        }
        public ActionResult GetData(string name, int age, string sex)
        {
            var a = name;
            var b = age;
            var c = sex;
            return Content("信息已经收到!");
        }
    }
}
后台代码

 

猜你喜欢

转载自www.cnblogs.com/vichin/p/9350545.html