Peter Smith
Peter Smith

Reputation: 5548

Embedding javascript variables within MVC razor syntax

I am using ajax to fill a series of dropdown list in an MVC 3 razor environment and am trying to create a general function to do this. The core bit of the function I am having problems with is

url: '@Url.Action("SecondaryList")'

where I want to replace "SecondaryList" with a JavaScript variable.

So

var myUrl = 'SecondaryList'
url: '@Url.Action(' + myUrl + ')'

I have no idea how to do it as the above does not work!

Many thanks in advance!

Upvotes: 1

Views: 682

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

You could use the .replace() javascript function. Start by declaring a javascript variable

var myUrl = 'SomeAction';

and then use a dummy placeholder with the server side Url.Action helper that you could replace with the javascript variable:

url: '@Url.Action("__url__")'.replace('__url__', myUrl)

Upvotes: 3

Related Questions