自定义ASP.NET MVC4中的路由

时间:2014-10-15 16:18:39

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing

执行搜索控制器 - 索引

public ActionResult Index(string parm1, string parm2)

目前网址显示/Search/Index?parm1=aa&parm2=bb

我想显示/ Search / aa / bb

我将mapRoute更改为:

  routes.MapRoute(
            name: "SearchList",
            url: "Search/{action}/{parm1}/{parm2}",
            defaults: new
            {
                Controller = "Search",
                action = "Index",
                parm1= UrlParameter.Optional,
                parm2= UrlParameter.Optional
            });
我错过了什么?

2 个答案:

答案 0 :(得分:0)

试试这个:

routes.MapRoute(
            name: "SearchList",
            url: "Search/{parm1}/{parm2}",
            defaults: new
            {
                Controller = "Search",
                action = "Index",
                parm1 = UrlParameter.Optional,
                parm2 = UrlParameter.Optional
            });

答案 1 :(得分:0)

以下是使用搜索字词进行网址更改的直接方法。这不是开箱即用的,它不会与您的路由表有任何确切的绑定,如果您更改了路由,则必须在javascript中手动修复它。此外,您可能需要在生成URL时进行一些空/空检查。

$("input.search_term").change(function (e){
    
    //Get search terms and build new url
    var parm1 = $("input.search_term[name='parm1']").val();
    var parm2 = $("input.search_term[name='parm2']").val();
    var newUrl = "/search/"+ parm1 + "/" + parm2;
    
    //Change the link url, can do same thing on a form action url as well
    $("a.search_link").attr("href",newUrl);
  
    //For showing the text below, not necessary
    $("b.t_link").html(newUrl);
  
  });
<input type="text" class="search_term" name="parm1" value="aa" />
<input type="text" class="search_term" name="parm2" value="bb" />

<a class="search_link" href="/search/aa/bb">Search</a>

<!--not necessary-->
<br />
<span>URL of the link will be: <b class="t_link"></b></span>

<!--I assume you use jquery, let me know if you don't-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>