Erick Velasco
Erick Velasco

Reputation: 124

How to use a var in ajax url with action razor syntax

I have a function that calls a method in controller through an Action URL, but I need use a parameter like name of Method, but this is not possible in this way.

function changeDropDownList(id, dropNameToChange, actionName, descriptionName) {

    var control = $('#'+dropNameToChange);
    control.prop("disabled", false);

    $.ajax({
        //Here I need use the actionName var, but only accept a string
        url: '@Url.Action(actionName, "ThirdPartiesDef")',
        dataType: "JSON",
        data: { id: id },
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            control.empty();
            $.each(result, function (index, item) {
                control.append(
                    $('<option/>', {
                        value: item.Id,
                        text: item[descriptionName]
                    })
                );
            });
        },
        error: function (error) {
            alert("Error: " + error);
        }
    });
}

I don't know so much of ajax and if you can say me some more easy method, it's ok.

Thank you for your help

Upvotes: 1

Views: 3097

Answers (2)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48407

You have to use JSON.stringify() method.

JSON.stringify() method turns a javascript object to json text and stores it in a string.

You specified contentType: "application/json; charset=utf-8", and the server waits to receive data in json format.

Also, you used wrong @Url.Action : @Url.Action(actionName, "ThirdPartiesDef")',.

One solution is to use .replace function:

'@Url.Action("myAction", "ThirdPartiesDef")'.replace('myAction', actionName).

In Razor every content using a @ block is automatically HTML encoded by Razor.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039080

You could use a placeholder inside the Url.Action server side Razor function that will be replaced by your javascript actionName variable on the client side:

url: '@Url.Action("#THE-ACTION#", "ThirdPartiesDef")'.replace('#THE-ACTION#', actionName)

which basically will emit the following markup inside the browser on the client:

url: '/#THE-ACTION#/ThirdPartiesDef/'.replace('#THE-ACTION#', actionName)

which after calling the changeDropDownList javascript function on the client it will replace the placeholder with the actionName javascript variable and you will end up with the correct url to use for your AJAX call.

As a side note you should remove the contentType: "application/json; charset=utf-8" parameter from your AJAX call because you are not sending any JSON at all in your data parameter.

Upvotes: 1

Related Questions