Charles
Charles

Reputation: 13

Send a value from Controller to Jquery

I have a MVC application.

The controller:

public ActionResult DescargaCsv()
{  
    // do stuff
    if (status != 0){
        return value to javascript and display an alert there
    }
    else{
        //do other stuff, this is OK
    }
}

The javascript:

function fnDownloadExcel() {
$.ajax({
    url: fnDownloadExcel?idArchivo=" + $("#idArchivo").val(),
    type: "POST",        
    success: function (data) {
    $("#idMessage").val(data[0]);
    if (data[0] == "R") {
        alert("Status: " + $("#idMensaje").val());
        }
    else {
        //do other stuff
         }                        
    }
}); 

How can I send to the javascript the value of "status" that I'm getting in the controller?

Upvotes: 1

Views: 144

Answers (2)

CoderZ
CoderZ

Reputation: 11

Controller:

public JsonResult DescargaCsv() {  
    // do stuff
    if (status != 0)
    {
        return Json(status);//return values you want 
    } 
    else
    {
        //do other stuff, this is OK
    }
}

Script:

function fnDownloadExcel() {
    $.ajax({
       url: fnDownloadExcel?idArchivo=" + $("#idArchivo").val(),
       type: "POST",        
       success: function (data) {
           alert(data);    
       },
       statusCode: {
           500: function(data) {
              alert(data);
           }
       }
    }); 
}

Upvotes: 0

mawburn
mawburn

Reputation: 2346

C#

public ActionResult DescargaCsv() {  
    // do stuff
    if (status != 0){
        return new HttpStatusCodeResult(500, "This is a bad status message");
    } else{
        //do other stuff, this is OK
    }
}

jQuery

function fnDownloadExcel() {
    $.ajax({
       url: fnDownloadExcel?idArchivo=" + $("#idArchivo").val(),
       type: "POST",        
       success: function (data) {
           $("#idMessage").val(data[0]);
           if (data[0] == "R") {
             alert("Status: " + $("#idMensaje").val());
          } else {
            //do other stuff
          }                        
       },
       statusCode: {
           500: function(data) {
                  alert(data);
           }
       }
    }); 
}

This is untested, but it should work.

Upvotes: 2

Related Questions