0

I'm building an ASP.NET MVC application with a lots of jQuery ajax calls (usually to refresh lists etc.). I'm using $.load mostly. The rebinding/action js scripts are naturally in Scripts folders in .js files. At this moment I'm holding all links in _Layout.cshtml like this

    var GET_ARTICLE_LIST = '@Url.Action("List","Article",null)';
    var GET_FILES_LIST = '@Url.Action("Files","Library", null)';

then I'm using it in a code like this

    $('.element').load(GET_ARTICLE_LIST);

is there any nicer way to pass ASP.NET MVC @Url.Action link to .js files?

1
  • try doing a console on that like console.log(GET_ARTICLE_LIST ) and see what's coming there Commented Feb 5, 2014 at 8:59

2 Answers 2

2

You could store the url in a data-attribute of the element that triggers the ajax call (i.e. a button or link etc)

<input type="submit" name="submit" data-url="@Url.Action("Action", "Controller")" />

var url = $(your_element).data('url');
$('.element').load(url);
Sign up to request clarification or add additional context in comments.

1 Comment

well, I guess it's the cleanest solution
-1

Have you tried to make a javascript function in the Layout that returns you the url? For example:

function GetUrl(controller, action){
    return '@Url.Action("ACTION", "CONTROLLER")'.replace('ACTION',action).replace('CONTROLLER',controller);
}

so you don't have to write all this urls.

4 Comments

@Url.Action executes on server so this will execute Url.Action("ACTION", "CONTROLLER") long before the js executes, which will most likely yield an error
Yes it does execute on the server. Thats why we have the replace statements after that.
There is no guarantee that the result of the call to @Url.Action will contain substrings "ACTION" and/or "CONTROLLER", this depends on how you have set up your routes.
There isn't any call here. You are just generating the url string. So if you are developing on localhost you will have the GetUrl function look like : function GetUrl(controller, action){ return 'localhost/CONTROLLER/ACTION'.replace('CONTROLLER',controller).replace('ACTION',action); } and when ever you call with with your parameters you will get the needed url

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.