Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yeah, very clunky. Actually you don't need absolute urls for your javascript. It can work with relative urls. For example:</p> <pre><code>@Html.Hidden("rt", Url.Content("~/")) </code></pre> <p>Now whether using a hidden field is a good thing or not is though to say without knowing more details about your scenario and what exactly you are trying to do in javascript. But let's consider a very common scenario. You want to AJAXify a form. In this case you would use HTML helpers in your view to generate the form and then:</p> <pre><code>$(function() { $('#myform').submit(function() { $.ajax({ url: this.action, type: this.method, data: $(this).serialize(), success: function(result) { // TODO: do something with the results } }); return false; }); }); </code></pre> <p>See how we no longer need any hardcoded urls or hidden fields fore the javascript. </p> <p>Or let's consider another scenario. You want to AJAXify an anchor. Same thing. You use <code>Html.ActionLink</code> to generate your anchor and then:</p> <pre><code>$(function() { $('#mylink').click(function() { $.get(this.href, function(result) { // TODO: do something with the results }); return false; }); }); </code></pre> <p>Or yet another scenario. You have some div container that you want to send an AJAX request to some controller action upon clicking on it. In this case you could use HTML5 data-* attributes on the div:</p> <pre><code>&lt;div id="mydiv" data-url="@Url.Action("Foo", "Home")"&gt;Some contents&lt;/div&gt; </code></pre> <p>and then:</p> <pre><code>$(function() { $('#mydiv').click(function() { $.get($(this).data('url'), function(result) { // TODO: do something with the results }); return false; }); }); </code></pre> <p>OK, now you see that you no longer need any hidden fields. There are always possibilities to do better.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload