OiO.lk Blog jQuery Passing a jQuery variable to @Url.Action in ASP.NET MVC
jQuery

Passing a jQuery variable to @Url.Action in ASP.NET MVC


This is an example of a function that takes the ID of a thumbnail image and when clicked brings up the full image in a modal:

$('.imageLandscapeFloatLeft').on('click', function () {
var vIDString = this.getAttribute('id');
if (vIDString.indexOf("image_") >= 0) {
    var vID = vIDString.substring(6);
    if ($.isNumeric(vID)) {
        jQuery.ajax({
            url: '@Url.Action("ReturnSoftwareImage", "Business")',
            type: 'POST',
            data: { ImageID: vID },
            success: function (response) {
                if (typeof (response) == 'object') {
                    var vAlt = (response.alt);
                    var vLink = (response.link);
                    ModalInformation(vAlt, vLink);

                }
                else {
                    ModalError(response);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                ModalError(textStatus + " - " + errorThrown);
            }
        })
    }
}
})

It works fine, but because there are so many pages using this function, I wanted to simplify the code and put a chunk on _Layout and just pass the parameters to it like this…

$('.imageLandscapeFloatLeft').on('click', function () {
var vIDString = this.getAttribute('id');
if (vIDString.indexOf("image_") >= 0) {
   
    OpenImageModal("Business", "ReturnImage", "ReturnWebImage", vIDString, "6");
}
})

function OpenImageModal(ControllerName, ActionResultName, ActionData, IDString, IDLength) {

var vID = IDString.substring(IDLength);
          
if ($.isNumeric (vID)) {
    alert(vID);
    jQuery.ajax({
        url: '@Url.Action()',
        type: 'POST',
        data: { ActionData: vID },
        success: function (response) {
            if (typeof (response) == 'object') {
                var vAlt = (response.alt);
                var vLink = (response.link);
                ModalInformation(vAlt, vLink);
            }
            else {
                ModalError(response);
            }

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            ModalError(textStatus + " - " + errorThrown);
        }
    })
}
}

I am trying to find a way to pass the variables (in this case ControllerName and ActionResultName) to the Ajax url @Url.Action() – but so far wrapping it in quotes and other methods have failed.



You need to sign in to view this answers

Exit mobile version