zoukankan      html  css  js  c++  java
  • asp.net mvc 自定义路由 【asp.net mvc 自学笔记】

    在很多地方会使用到mvc的路由设置 优化SEO 使客户在访问页面的时候更加的明了自己所在的位置,便于多参数的验证后的传递等等

     
    设置mvc的路由在  里的

    public static void RegisterRoutes(RouteCollection routes) 方法里 
    方法里已经有一个默认的路由
     
    routes.MapRoute(
                    "Default", // 路由名称
                    "{controller}/{action}/{id}", // 带有参数的 URL
                    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
                );
    

      

     
     但是在网站功能复杂需求多样的情况下不能满足使用。
    所以需要自己设置路由
     
    自己设置路由也是非常简单的 自己动手做一遍 大致就能感悟到路由设置的方法
     
    如 我设置了这个路由
     
    routes.MapRoute(
                    "Yahui",
                    "yahui/{year}/{month}/{day}",
                    new
                    {
                        controller = "Yahui",
                        action = "Index",
                        year = "",
                        month = "",
                        day = ""
                    },
                    new  {
                        year = @"\d+",
                        month=@"\d+",
                        day=@"\d+"
                    }
                    );
    这个路由规定了 控制器为Yahui ,action为Index时 参数有是三个 分别是yuear month day  接下来在    new  {
                        year = @"\d+",
                        month=@"\d+",
                        day=@"\d+"
                    }里使用正则表达式 规定了 year类型为整数 month和day也是
     
    这样一个自定义路由就设计好了 下面要使用它了
     
     创建一个名为Yahui的控制器

     
    把action  index()改为
    public ActionResult Index(int year,int month,int day)
            {
                ViewBag.year = year;
                ViewBag.month = month;
                ViewBag.day = day;
                return View();
            }
    

      

    添加上year month day三个参数
    然后添加index视图 
     
    Index.cshtml里为
     
    @{
        ViewBag.Title = "index";
    }
     
    <h2></h2>
    @{
        int year = ViewBag.year;
        int month = ViewBag.month;
        int day = ViewBag.day;
        <label style="background-color:Red">year:@year,month:@month,day:@day</label>
     }
     
    生成网站 测试一下
     

    如图 这个asp.net mvc 自定义路由的示例网页就ok了
  • 相关阅读:
    MySQL 索引优化指南
    Servlet,Tomcat,Jetty,Netty,Mina 对比
    Linux 磁盘IO速度测试
    flume 数据链路问题排查
    MySQL 强行kill后启动失败问题:[ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
    hdfs web界面介绍
    python2/python3 编码问题
    Spark WARN Utils: Service 'sparkDriver' could not bind on port 0. Attempting port 1.
    python2 升级到 python3
    万维网的信息检索系统【计算机网络】
  • 原文地址:https://www.cnblogs.com/yahue/p/asp_mvc_set_route_by_myself.html
Copyright © 2011-2022 走看看