Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Separate js File And use Url Helpers in it with ASP.NEt MVC 3 and Razor View Engine

I ask a similar question here and Darin Dimitrov answer that we can't use Url helper like $.ajax({ url: '@Url.Action("Index")', . . . in separate js file so what is your suggestion to use Url helper in view page and pass it to javascript, I don't want to use hard code url, I need to find it with Url helper.?

like image 586
Saeid Avatar asked Mar 29 '12 08:03

Saeid


2 Answers

Use a hidden field to store your url, then use javascript to read the hidden field, then use that in your code. That way you can keep the JS file separate to the view. Something like this:

//In Your View
    @Html.Hidden("MyURL", Url.Action("Index"))

//In Your JS
    var myUrl = $("#MyURL").val();

    $.ajax({ url: myUrl , . . .
like image 101
raklos Avatar answered Oct 13 '22 14:10

raklos


The easiest way is just to create a global variable called something and just reference to it in your external JS

var baseURL = '@Url.Action("Index")';

Inside your external JS

$.ajax({ url: baseURL + "Action"
like image 44
Simon Edström Avatar answered Oct 13 '22 15:10

Simon Edström