How to change Action according to condition in Ajax url?

0

I have the following sript:

$('a[id^=asociar-]').click(function (e) {

        e.preventDefault();

        var params = {
            id: parseInt($(this).attr('id').substring(8)),
            proveedorId: $('#proveedorId').val()
        };

        var asociado = $(this).find('input').val();
        var actionName = (asociado === 'False') ? 'Asociar' : 'Desasociar';

        var jsUrl = '@Url.Action("##", "Administrador")';
        $.ajax({
            url: jsUrl.replace('##', actionName),
            type: "post",
            data: params,
            cache: false,
            success: function (result) {
                if (result.flag) {
                    $("#asociar-" + params.id).removeClass("fa-square-o").addClass("fa-check-square-o");
                }
            }
        });
    });

I need the ActionName to be dynamic according to the condition, in the script the Replace is not working inside the ajax, it generates the error:

NetworkError: 404 Not Found - link Administrator /% 23% 23 "

Any ideas on how to achieve this?

    
asked by jose luis garcia 07.05.2016 в 04:22
source

1 answer

2

The problem is in the characters you use to replace in the url.

var jsUrl = '@Url.Action("##", "Administrador")';

The Url.Action method will return a string with the url to the indicated action, but make an UrlEncode of this string to convert it to a valid url. Which means that the url would look like:

var jsUrl = '/Administrador/%23%23';

With which, when doing the replace will not replace anything.

You can try other valid characters in a url (such as scripts) and it will work for you.

    
answered by 07.05.2016 / 06:06
source