MVC 5 doesn't seem to like JavaScript that much. I am creating link in JavaScript to a success method in my Ajax call.


@Html.ActionLink("Amount", "Action", "Controller", new { id1 = "a", id2 ="b"}, new { target = "_blank"})


$('#element').html('<a href="' + '@Url.Action("Action", "Controller", new { id1= "a", id2= "__id2__" })'.replace("__id2__", id2) + '" target="_blank">' + data[1] + '</a>');

This link works, but, I am not sure it's the best solution. Tried with a onclick method on the element instead, and with a separate method for handling the link, but still doesn't really get around this replacing.

And if it has more parameters should I just be chaining them?

.replace("__id2__", id2).replace("__id3__", id3).replace("__id4__", id4) etc
  • \$\begingroup\$ While we have the tag system to avoid the usage of tags in the title, your code interacts with that language, so that's okay (just for Razor), please remember for future that (like in this case with JavaScript), the tag shouldn't be put in the title. \$\endgroup\$
    – Quill
    Aug 6 '15 at 9:03

I can't really comment on your structure in Razor, as I am unfamiliar with that framework, however, your replacing structure could be improved.

By using a function, alongside a dictionary, you can simplify this greatly.

function massReplace(str, dict){
    for (var i in dict){
        str = str.replace(i, dict[i]);
    return str;

Whilst also converting the "__id3__", id3 structure into:

var dict = {
    "__id2__": id2,
    "__id3__": id3, 
    "__id4__": id4

And then simply:

$('#element').html('<a href="' + massReplace('@Url.Action("Action", "Controller", new { id1= "a", id2= "__id2__" })', dict) + '" target="_blank">' + data[1] + '</a>');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.