Paul
Paul

Reputation: 3954

Can I pass a javascript variable to inline ASP.NET code?

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!

Upvotes: 2

Views: 882

Answers (2)

tedski
tedski

Reputation: 2311

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.

Upvotes: 3

eouw0o83hf
eouw0o83hf

Reputation: 9598

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.

Upvotes: 1

Related Questions