Url.Content for javascript

I am currently using this approach to get the correct relative URI (regardless of deployment situation). Razor Code (asp.net mvc 3):

@section JavaScript { <script type="text/javascript"> var _getUrl = "@Url.Content("~/bla/di/bla")"; </script> } 

Separate js file:

 $.ajax({ url: _getUrl, 

Do you think there is a better approach?

+7
source share
2 answers

Personally, I prefer to use data- * HTML5 attributes or include a URL as part of some DOM element, which I unobtrusively AJAXify.

The fact is that you never write the so-called $.ajax calls. You write them to match some DOM events. For example, the click of an anchor. In this case, this is trivial, you just use the HTML helper to create this anchor:

 @Html.ActionLink("click me", "someAction", "somecontroller", new { id = "123" }, new { @class = "link" }) 

and then:

 $('.link').click(function() { $.ajax({ url: this.href, type: 'GET', success: function(result) { ... } }); return false; }); 

or maybe you are an AJAXifying form:

 @using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Post, new { id = "myForm" })) { ... } 

and then:

 $('#myForm').submit(function() { $.ajax({ url: this.action, type: this.method, data: $(this).serialize(), success: function(result) { ... } }); return false; }); 

Another example would be the use of data- * HTML5 attributes when the corresponding URL is not available in the corresponding DOM element. Suppose you want to trigger a controller action using AJAX when changing a drop-down list change. Think, for example, cascading ddls.

Here's what the dropdown menu looks like:

 @Html.DropDownListFor(x => x.SelectedValue, Model.Values, new { id = "myDdl", data_url = Url.Action("SomeAction") }) 

and then:

 $('#myDdl').change(function() { var url = $(this).data('url'); var selectedValue = $(this).val(); $.getJSON(url, { id: selectedValue }, function(result) { ... }); }); 

So, as you can see, you really don't need this javascript _getUrl global variable that you specified in your view.

+6
source

I would do the following:

Razor C # script before Javascript

 @{ var myUrlString = Url.Action("ActionName", new { controller="ControllerName" }); } 

Javascript

 $.ajax('@myUrlString',{ // options }); 

You can also use Url.RouteUrl or Url.HttpRouteUrl .

EDIT - show an example with a split JS file

Razor

 @{ var myServerGeneratedValue = Url.Action("ActionName", new{controller="ControllerName"}); } <script type="text/javascript"> var myHelperObject = new MyHelperObject(); myHelperObject.Init('@myServerGeneratedValue'); </script> 

Js file

 var MyHelperObject = function(){ this.Init = function(serverGeneratedValue){ // do something with serverGeneratedValue }; }; 
0
source

All Articles