jQuery,Razor,Variables,URL ...如何使用@ Url.Action

时间:2013-10-02 19:16:31

标签: jquery asp.net-mvc razor routing

我有 CodesController ,而Index操作看起来像这样。

public ActionResult Index(int id, string manufacturerName)

我希望网址看起来像 http://www.domain.com/codes/ [id] / [manufacturerName] 但是我目前正在使用的代码看起来像 http://www.domain.com/codes/ [id]?manufacturerName = [manufacturerName]

<script type="text/javascript">
    $(function() {
        $('#btnNext').click(function () {
            var _id = $('#ddlManufacturers').val();
            var _manufacturerName = $('#ddlManufacturers').text();
            var url = '@Url.Action("Index", "Codes", new { id = "_id", manufacturerName = "_manufacturerName" })'
            .replace('_id', _id).replace('_manufacturerName', _manufacturerName.toLowerCase().trim());
            window.location.href = url;
        });
    });

这就是我现在正在做的事情,不知道如何正确地做到这一点,所以URL以我想要的方式结束。代码

2 个答案:

答案 0 :(得分:1)

根据我的理解,你需要添加一个像

这样的路线
routes.MapRoute(
    name: "CodesRoute",
    url: "{controller}/{action}/{id}/{manufacturerName}",
    new { controller = "Codes",  action = "Index",
        manufacturerName = UrlParameter.Optional 
    }
);

之后,您可以使用Html.RouteLinkUrl.RouteUrl

当您使用它时,JavaScript Url.RouteUrl将非常有用

var url = '@Url.RouteUrl("CodesRoute", new { id = "_id", manufacturerName = "_manufacturerName" })'

答案 1 :(得分:0)

您需要一条新路线:

routes.MapRoute(
    name: null,
    url: "{controller}/{action}/{id}/{manufacturerName}",
    defaults: new { 
        controller = "Home", 
        action = "Index", 
        id = UrlParameter.Optional, 
        manufacturerName = UrlParameter.Optional 
    }
);