I am using $ajax jquery function on partial razor view to get another partial view along with strongly typed model data from controller to page--> display in specific div. Now if data model data is there it works but in case if there is no model data, I am passing json response so that I can check on razor view in order to avoid null exception. My issue is done method in $ajax is not calling plus json response, I don't know where I am doing wrong
$(document).ready(function () {
/*Address*/
$.ajax({
url: '@Url.Action("DisplayStudentAddress")',
type: "GET",
cache: false
}).done(function (data, textStatus, jqXHR) {
alert(data.Response);
$('#studentAddressDisplay').html(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(jqXHR +" "+textStatus+" "+errorThrown);
});
});
[HttpGet]
[Authorize]
public ActionResult DisplayStudentAddress()
{
int _studentEntityID = 0;
_studentEntityID = _studentProfileServices.GetStudentIDByIdentityUserID(User.Identity.GetUserId());
Address _studentAddressModel = new Address();
_studentAddressModel = _studentProfileServices.GetStudentAddressByStudentID(_studentEntityID);
if (_studentAddressModel != null)
{
return PartialView("DisplayStudentAddress_Partial", _studentAddressModel);
}
else
{
return Json(new { Response = "Provide Your Address Detail!" });
}
}
#endregion
I have check in debugging, json is called in controller but it alert error in ajax
If your server returns empty string for a json response, jQuery treats it as failed. and empty string is considered invalid json.
As per official document here.
As of 1.9, an empty string returned for JSON data is considered to be malformed JSON (because it is); this will now throw an error.
try below code instead with using .always
:-
$.ajax({
url: '@Url.Action("DisplayStudentAddress")',
type: "GET",
cache: false
}).always(function (data, textStatus, jqXHR) {
alert(data.Response);
$('#studentAddressDisplay').html(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(jqXHR +" "+textStatus+" "+errorThrown);
});
Because .done
is executed only if everything works successfully so if there will be something wrong .done
will not be called. But the always
method will always get triggered regardless your ajax request works or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With