简体   繁体   中英

C# mvc - Controller returns either partial view or json data

I am making an ajax call to the controller. The controller will return a string if the execution is successful or it will return a partial view if an error is found. I am forcing it to fail, but it still goes into the success event in the ajax.

How do I go about getting it to display the partial view when failed OR just alert the string value when successful?

Ajax call:

$.ajax({
    url: '@Url.Action("GetItem","Home")',
    data: { },
    success: function (result) {
        alert(result);
    },
    error: function (result) {
        $(".MyDiv").html(result);
    }
})

Controller:

public ActionResult GetItem([DataSourceRequest]DataSourceRequest request)
{
    try
    {
        throw new Exception("ERROR");

        //return Json("Success", JsonRequestBehavior.AllowGet);
    }

    catch (Exception ex)
    {
        AlertMessage alertMessage = new AlertMessage();
        alertMessage.MessageText = "A critical error has occurred, please contact your administrator.";
        alertMessage.ErrorMessageText = ex.ToString();
        alertMessage.MessageHeading = "Critical Error";

        return PartialView("~/Views/Common/ErrorMessageDisplay.cshtml", alertMessage);
    }
}

Function you've provided as error argument of ajax call will be called if the request fails. This means response status code is one of 40* or 50* codes.

But when you're returning PartialView from your controller, actually response has status code 200 that is "OK" - that's why success function is being called.

You can modify your controller code by adding Response.StatusCode = 500; just before return PartialView(... , and this should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM