I have this ActionLink.
@Html.ActionLink("Link", "action", "controller", null, htmlAttributes: new {@class = "menuLink"})
I have to set routeValues to null
because I don't know the value at compiletime. They are recieved from the selectedvalue of some dropdowns at runtime.
Hence, I am trying to augment the routevalues at runtime with JavaScript. I can't see what other choise I have.
I use the CSS class menuLink
on the ActionLink to catch the event.
$(".menuLink").click(function () {
var $self = $(this),
routeValue1 = getFromDropdown1(),
routeValue2 = getFromDropdown2(),
href = $self.attr("href");
// ???
});
How can I add the routevalues to make the href correct?
I want the URL to be something like this:
http://localhost/mySite/controller/action/2/2
My focus is on the /2/2
part..
I have tryed this
$self.attr("foo", routeValue1);
$self.attr("bar", routeValue2);
But then I get a URL like this:
http://localhost/mySite/controller/action?foo=2&bar=2
And it doesn't work with my routes.MapeRoute
routes.MapRoute(
name: "Authenticated",
url: "{controller}/{action}/{foo}/{bar}",
defaults: new { controller = "Home", action = "WelcomePage", Foo = "0", Bar = "0" }
);
I don't know if Foo = "0", Bar = "0"
is the problem.
Solution added. Thanks to @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);
I'm not sure this is the best way of doing this, but I'll provide you with my solution to this problem. The main idea is to generate the link with all required parameters and format the
href
with javascript, likestring.Format
in c#.The helper will generate the correct url, which according to your route configuration will look like this:
You can check how to implement one here. If you are using jQuery validation plugin you can utilize the built in format function.
Do not concatenate route parameters to the href like this
href +'/'+ routeValue1 +'/'+routeValue2
, the url will result in 404 if you change your route configuration. You should always generate urls with Url helpers and avoid hadcoding them in the javascript code.