asp.net mvc - Url.Content for javascript -


i use approach obtain correct relative uri (independent 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 reckon there better approach?

personally prefer using html5 data-* attributes or including url part of dom element unobtrusively ajaxify.

the thing never write $.ajax calls flying around that. write them correspond dom events. example clicking of anchor. in case it's trivial, use html helper generate 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 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 use html5 data-* attributes when appropriate url not available on corresponding dom element. suppose want invoke controller action ajax when selection of dropdown changes. think example cascading ddls.

here's how dropdown might 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 can see don't need _geturl global javascript variable declared in view.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -