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.