Reputation: 1
From an ajax function, I call an MVC controller method and return a -1 if the method fails. How do I code the ajax function to receive the -1 so that I can execute a javascript alert?
function RejectButtonProcess()
{
// This will execute the method in the specified controller.
$.ajax({
type: "POST",
url: '@Url.Action("NHPDAdminRejectAddress", "Home")',
error: function(XMLHttpRequest, textStatus, errorThrown)
{
//alert("Status: " + textStatus); alert("Error: " + errorThrown);
alert("An error occurred during the reject process. Contact the IT department.");
}
});
}
Upvotes: 0
Views: 80
Reputation: 2385
Although sending back a response and checking the data object in the callback (as explained above by @Richard and @Jatin) will work, I tend to follow the following pattern of rolling my own AjaxResult object, hydrating this object with the model state validity, the success state, as well as any data I need to pass back to the $.ajax success callback function. This enables a flexible and elegant solution in handling $.ajax requests. For example:
// custom ajax request result class
public class AjaxResult
{
public bool IsValid { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
public Dictionary<string, object> Data { get; set; }
public AjaxResult()
{
Data = new Dictionary<string, object>();
}
public void AddData(string dataKey, object dataValue)
{
if (dataKey != null && !Data.ContainsKey(dataKey))
{
Data.Add(dataKey, dataValue);
}
}
}
// controller
public ActionResult NhpdAdminRejectAddress(NhpdAdminViewModel model)
{
AjaxResult result = new AjaxResult();
if (ModelState.IsValid)
{
// do something
result.AddData("Code", -1);
result.IsValid = true;
result.Success = true;
}
return Json(result);
}
// ajax post request
$.ajax({
type: "POST",
url: '@Url.Action("NHPDAdminRejectAddress", "Home")',
data: JSON.stringify(model),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result != null && result.Data != null && result.Data.Code != null)
{
int code = result.Data.Code;
}
},
error: function () {
// handle error
}
});
Upvotes: 0
Reputation: 4288
You can do it as follows,
$.ajax({
type: "POST",
url: '@Url.Action("NHPDAdminRejectAddress", "Home")',
data: JSON.stringify(model), \\ Pass data if any
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if(result == -1) { \\Check Result
alert("Error");
}
},
error: function () {
}
});
Upvotes: 0
Reputation: 6344
Add the success callback:
success: function (data, textStatus, jqXHR) {
// process the data
},
The data
variable coming back will contain the return code (probably in JSON, depending on how you set up your endpoint).
Upvotes: 1