我有这个ActionLink。
@Html.ActionLink("Link", "action", "controller", null, htmlAttributes: new {@class = "menuLink"})
我必须将routeValues设置为,null
因为我在编译时不知道该值。它们是在运行时从某些下拉列表的selected值中接收的。
因此,我试图在运行时使用JavaScript来扩充routevalues。我看不到我还有其他选择。
我menuLink
在ActionLink上使用CSS类来捕获事件。
$(".menuLink").click(function () {
var $self = $(this),
routeValue1 = getFromDropdown1(),
routeValue2 = getFromDropdown2(),
href = $self.attr("href");
// ???
});
如何添加路由值以使href正确?
我希望网址是这样的:
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.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);
我不确定这是否是最佳方法,但是我将为您提供解决此问题的方法。主要思想是生成具有所有必需参数的链接,并href
使用javascript设置格式,例如string.Format
在c#中。
- 生成链接:
@Html.ActionLink("Link", "action", "controller",
new { Foo = "{0}", Bar = "{1}"}, htmlAttributes: new { @class = "menuLink" })
帮助程序将生成正确的URL,根据您的路由配置,该URL如下所示:
<a href="http://website.com/controller/action/{0}/{1}" class="menuLink">Link</a>
- 编写
format
函数。
您可以在此处检查如何实施。如果您使用的是jQuery验证插件,则可以利用内置的format函数。
href
javascript中的Format属性:
$(".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
,如果您更改路由配置,则网址将为404。您应该始终使用Url帮助程序生成网址,并避免在JavaScript代码中对它们进行过编码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句