简体   繁体   中英

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

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, like string.Format in c#.

  1. Generate the link:
@Html.ActionLink("Link", "action", "controller",
    new { Foo = "{0}", Bar = "{1}"}, htmlAttributes: new { @class = "menuLink" })

The helper will generate the correct url, which according to your route configuration will look like this:

<a href="http://website.com/controller/action/{0}/{1}" class="menuLink">Link</a>
  1. Write the format function.

You can check how to implement one here . If you are using jQuery validation plugin you can utilize the built in format function .

  1. Format href attribute in your javascript:
$(".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);
});

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.

You can change the href attribute of anchor tag dynamically like below.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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