1
\$\begingroup\$

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

Razor:

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

JavaScript:

$('#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
Quill
12k5 gold badges41 silver badges93 bronze badges
asked Aug 6, 2015 at 7:40
\$\endgroup\$
1
  • \$\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\$ Commented Aug 6, 2015 at 9:03

1 Answer 1

1
\$\begingroup\$

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>');
answered Aug 6, 2015 at 9:13
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.