ASP.NET MVC AJAX call return Error Message in parallel with Partial View -
the scenario in asp.net mvc (4,5) maxing ajax call returns partial view. based on different situations may need return error message - display user example..
my current approach this.
in js:
$.ajax({ url: url, type: "post", data:{ id: id}, success: function (response) { $("#container").html(response); }, error: function (er) { if (er.status == "405") {// someth } else if (er.status == "406") {// someth else } } });
in controller:
public actionresult servermethod(int id) { if (id = 0) return new httpstatuscoderesult(405); if (id = 1) return new httpstatuscoderesult(406); //otherwise.. return partialview("view", model); }
i aware hack , not proper solution.. there better way of doing this?
you return jsonresult
in fail cases. add properties want json.
something this:
public actionresult servermethod(int id) { if (id == 0) { return json(new { failed = true, failtype = "type1", // whatever makes sense //otherrelevantproperty = whatever }); } if (id == 1) { return json(new { failed = true, failtype = "type2", // whatever makes sense //otherrelevantproperty = whatever }); } //otherwise.. return partialview("view", model); }
in ajax call this:
$.ajax({ url: url, type: "post", data:{ id: id}, done: function (response) { if (response.failed) { // switch response.failtype , use relevant // json properties created in controller } else { $("#container").html(response); } } });
if absolutely need return failed status code, set before returning json such as:
if (id == 0) { response.statuscode = 500; return json(new { failed = true, failtype = "type1", // whatever makes sense //otherrelevantproperty = whatever }); }
and handle failed case in fail
callback:
$.ajax({ url: url, type: "post", data:{ id: id}, done: function (response) { $("#container").html(response); }, fail: function(xhr) { var response = json.parse(xhr.responsetext); if (response.failed) { // switch response.failtype , use relevant // json properties created in controller } } });
please note haven't tested particular code , demonstration only. am, however, using similar set-up in projects.
Comments
Post a Comment