Send ajax GET request to ASP .NET Web API

Viewed 3104

I use the following ajax script.

$.ajax({
            dataType: 'json',
            url: url,
            data:  tuDispId,
            type: "GET",
            success: function (data) {
                bindData(data);
                $("#alert-placeholder").empty();
                $('#alert-placeholder').removeClass('alert alert-danger');
            },
            error: function (xhr, textStatus, errorThrown) {
                $('#alert-placeholder').addClass('alert alert-danger');
                $('#alert-placeholder').html(errorThrown);
            }
        });

The attribute Route in Web API before method.

[Route("api/tudisp/Edit/{tuDispId}")]
        public IHttpActionResult Edit(int tuDispId)
{
}

The genarated request from ajax.

http://localhost:xxxxx/api/tudisp/Edit/?179

How to force ajax to not generate sign '?' by id parameter.

1 Answers

The simplest way to do it is to change the url property of the Ajax options...

$.ajax({
    dataType: 'json',
    url: "http://localhost:xxxxx/api/tudisp/Edit/" + tuDispId,
    type: "GET",
    success: function (data) {
        bindData(data);
        $("#alert-placeholder").empty();
        $('#alert-placeholder').removeClass('alert alert-danger');
    },
    error: function (xhr, textStatus, errorThrown) {
        $('#alert-placeholder').addClass('alert alert-danger');
        $('#alert-placeholder').html(errorThrown);
    }
});

GET parameters are automatically appended to the Url as a querystring, which is fine if that's what your application is expecting, but not when you're using routing as you are.

However, if you wanted to modify existing Ajax requests you can use prefiltering. This example modifies the Url of the ajax call, replacing {variable} with a given value from the data object...

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    options.data = ""; // this removes the querystring
    for (key in originalOptions.data) {
        options.url = options.url.replace("{" + key + "}", originalOptions.data[key]);
    }
});

$.ajax({
    url: "http://localhost:xxxxx/api/tudisp/Edit/{tuDispId}",
    data: {
        "tuDispId": 179
    }
});

If you wanted to use something like that then I'd strongly recommend spending a bit of time making it more robust, but it's an example of how you could do what you want.

Related