繁体   English   中英

如何使用ASP.NET MVC 5中的JavaScript在运行时使用路由值来增强actionlink?

[英]How to augment actionlink with route values at runtime with JavaScript in ASP.NET MVC 5?

我有这个ActionLink。

@Html.ActionLink("Link", "action", "controller", null, htmlAttributes: new {@class = "menuLink"})

我必须将routeValues设置为null因为我不知道编译时的值。 它们在运行时从某些下拉列表的选定值中收到。

因此,我试图用JavaScript在运行时增加routevalues。 我看不出有什么别的选择。

我在ActionLink上使用CSS类menuLink来捕获事件。

$(".menuLink").click(function () {
    var $self = $(this),
        routeValue1 = getFromDropdown1(),
        routeValue2 = getFromDropdown2(),
        href = $self.attr("href");

     // ???
});

如何添加路由值以使href正确?

我希望URL是这样的:

http://localhost/mySite/controller/action/2/2

我的重点是/2/2部分..

我试过这个

$self.attr("foo", routeValue1);
$self.attr("bar", routeValue2);

但后来我得到一个这样的URL:

http://localhost/mySite/controller/action?foo=2&bar=2

它不适用于我的routes.MapeRoute

routes.MapRoute(
    name: "Authenticated",
    url: "{controller}/{action}/{foo}/{bar}",
    defaults: new { controller = "Home", action = "WelcomePage", Foo = "0", Bar = "0" }
);

我不知道如果Foo = "0", Bar = "0"就是问题所在。

解决方案补充 感谢@Zabavsky

if (!String.format) {
    String.format = function (format) {
        var args = Array.prototype.slice.call(arguments, 1);
        return format.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
                ? args[number]
                : match
            ;
        });
    };
}

var href = $self.attr("href");
var hrefDecoded = decodeURIComponent(href);
var hrefFormatted = String.format(hrefDecoded, 2, 1); // 2 and 1 test only..
$self.attr('href', hrefFormatted);

我不确定这是最好的方法,但我会为你提供解决这个问题的方法。 主要思想是生成包含所有必需参数的链接,并使用javascript格式化href ,如c#中的string.Format

  1. 生成链接:
@Html.ActionLink("Link", "action", "controller",
    new { Foo = "{0}", Bar = "{1}"}, htmlAttributes: new { @class = "menuLink" })

帮助器将生成正确的URL,根据您的路由配置,它将如下所示:

<a href="http://website.com/controller/action/{0}/{1}" class="menuLink">Link</a>
  1. format功能。

你可以在这里查看如何实现一个。 如果您使用的是jQuery验证插件,则可以使用内置格式函数

  1. 在javascript中格式化href属性:
$(".menuLink").click(function () {
    var routeValue1 = getFromDropdown1(),
        routeValue2 = getFromDropdown2(),
        url = decodeURIComponent(this.href);

    // {0} and {1} will be replaced with routeValue1 and routeValue1
    this.href = url.format(routeValue1, routeValue2);
});

不要将路由参数连接到href,如此href +'/'+ routeValue1 +'/'+routeValue2 ,如果更改路由配置,则url将导致404。 您应始终使用Url助手生成网址,并避免在javascript代码中对其进行编码。

您可以动态更改锚标记的href属性,如下所示。

$(".menuLink").click(function () {
    var $self = $(this),
        routeValue1 = getFromDropdown1(),
        routeValue2 = getFromDropdown2(),
        href = $self.attr("href"),
        editedHref = href.split('?')[0];

    $self.attr('href', editedHref+'/'+ routeValue1  +'/'+routeValue2 );
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM