Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url.Content for javascript

I currently use this approach to obtain the correct relative URI (independent of the 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 reckon there is a better approach?

like image 932
cs0815 Avatar asked Apr 05 '13 12:04

cs0815


1 Answers

Personally I prefer using HTML5 data-* attributes or including the URL as part of some DOM element that I unobtrusively AJAXify.

The thing is that you never write $.ajax calls flying around like that. You write them to correspond to some DOM events. Like for example clicking of an anchor. In this case it's trivial, you just use an HTML helper to generate 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 AJAXifying a 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 to use HTML5 data-* attributes when an appropriate url is not available on the corresponding DOM element. Suppose that you want to invoke a controller action with AJAX when the selection of a dropdown changes. Think for example cascading ddls.

Here's how your dropdown might look 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 don't really need this _getUrl global javascript variable that you declared in your view.

like image 104
Darin Dimitrov Avatar answered Oct 21 '22 08:10

Darin Dimitrov