2

I have found countless examples and posts about passing "code behind" variables to Javascript, but I'm wondering if there is a way to do the opposite.

In my view, I'm trying to dynamically create a Url using an ASP helper class and a variable from javascript. What I would like to do is something like:

var url = '@Url.Action("' + actionname + '", "controller")';

... where actionname is predetermined by some other logic. This won't work because I can't break up the inline code like that.

Anybody else tried to do something like this before or have any ideas?

Thanks!

1
  • 1
    That's impossible. The Javascript variable only exists on the client. Commented Mar 6, 2012 at 16:02

2 Answers 2

3

It's messy, but I've sometimes used a HiddenField to pass a value.

ASP:

<asp:HiddenField id="hfStuff" runat="server" />

jQuery:

$("#<%= hfStuff.ClientID %>").val("my value");

you can then access hfStuff.Value from the codebehind.

Like I said, messy, but gets the job done sometimes.

Sign up to request clarification or add additional context in comments.

Comments

1

If actionname is a javascript variable, you cannot do this: the @Url.Action method is executed on the server side, before being returned to the client. Thus, the javascript, which is executed on the client, cannot send information into the @Url.Action call.

If this is still the case, you could just pass the actionname as an arg to an Action that determines where to route it.

1 Comment

Thanks, this makes a lot more sense when you think about where the code is executed.

Your Answer

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.