0

I want to redirect the user to a url in a javascript function.

editClick: function () {
            var myid = 1;
            location.href = '<%= Url.Action("ActionName", "ControllerName", new { id = myid})%>';

        };

But 'myId' does not exist in the current context. How do I use a js variable in Url.Action?

2
  • That doesn't make sense. You cannot mix server- and client- side code. Commented May 2, 2013 at 15:32
  • I guess I shouldn't be using url.action and use an explicit url path. Commented May 2, 2013 at 15:42

1 Answer 1

1

An approach that I've taken in the past is to generate the link in the view like so:

<div class='clickmaster'>
  <div class='clicker' id='@Url.Action("ActionName", "ControllerName", new { id = Model.Id })'>
    Show Something Here
  </div>
  <div class='clicker' id='@Url.Action("ActionName", "ControllerName", new { id = Model.Id })'>
     Show Something Here
  </div>
</div>

Then in the javascript I defined a function like this:

$(function() {
   $('.clickmaster').on('click', '.clicker' , function() { location.href = this.id; })
});
Sign up to request clarification or add additional context in comments.

3 Comments

I really like that approach. Thanks!
You are welcome. The best way to show appreciate on SO is to accept answers and vote up when you are able.
@duyn9uyen: The better way to do this is a data-* attribute. (especially since IDs must be unique)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.