I need routing info for my javascript logic on the client. I have a workable solution right now but it feels kind of clunky. I am injecting a hidden field on the page. I’m thinking there has to be a better way. This is what i’m currently doing:
<input type="hidden" id="rt" value="@string.Format("{0}://{1}{2}",Request.Url.Scheme,Request.Url.Authority,Url.Content("~"))"/>
Yeah, very clunky. Actually you don’t need absolute urls for your javascript. It can work with relative urls. For example:
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:
See how we no longer need any hardcoded urls or hidden fields fore the javascript.
Or let’s consider another scenario. You want to AJAXify an anchor. Same thing. You use
Html.ActionLinkto generate your anchor and then: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:
and then:
OK, now you see that you no longer need any hidden fields. There are always possibilities to do better.