Reputation: 413
Hi all I'm using ajax to call detail model by Id. But I want to display a message if model return data is null. How do I ?
my code ajax to display details model
$('#PGId').blur(function () {
var errormsg = "";
var id = $('#PGId').val();
$.ajax({
type: "GET",
url: '@Url.Action("GetDetailPG", "TimeSheetHeader")',
data: { pgId: id },
dataType: "json",
success: function (data) {
success: function (data) {
if (data.isValid) {
$("#FullName").text(data.FisrtName + " " + data.LastName)
$('.Shiff[value="' + data.ShiffId + '"]').prop('checked', true)
}
else {
alert(data.error);
}
},
},
error: function () {
}
});
})
my controller to bind data
[HttpGet]
public ActionResult GetDetailPG(string pgId)
{
PGProfileViewModel pgProfileModel = new PGProfileViewModel();
pgProfileModel.PGId = pgId;
var query = _pgProfileService.GetPGProfileById(pgProfileModel.PGId);
var model = query.ToViewModel();
if (model == null)
{
return Json(new {isValid = false, error = "Error Message"}, JsonRequestBehavior.AllowGet);
}
else
{
model.LastName = query.LastName.Trim();
model.FisrtName = query.FisrtName.Trim();
model.ShiffId = query.ShiffId;
return Json(new { model = model , isValid = true }, JsonRequestBehavior.AllowGet);
}
}
Upvotes: 2
Views: 13406
Reputation: 4233
If you returns a json
object (as business model error) the javascript data
value (which has the request result) will never be null.
You can try an approach like this:
C#
[HttpGet]
public ActionResult GetDetailPG(string pgId)
{
PGProfileViewModel pgProfileModel = new PGProfileViewModel();
pgProfileModel.PGId = pgId;
var query = _pgProfileService.GetPGProfileById(pgProfileModel.PGId);
var model = query.ToViewModel();
if (model == null)
{
return Json({
isValid: false,
error: "Your error message"
}, JsonRequestBehavior.AllowGet);
}
else
{
model.LastName = query.LastName.Trim();
model.FisrtName = query.FisrtName.Trim();
model.ShiffId = query.ShiffId;
return Json({
model: model,
isValid: true
}, JsonRequestBehavior.AllowGet);
}
}
JS
//success function of your ajax request.
success: function (data) {
if (data.isValid) {
$("#FullName").text(data.FisrtName + " " + data.LastName)
$('.Shiff[value="' + data.ShiffId + '"]').prop('checked', true)
}
else {
alert(data.error);
}
}
Upvotes: 2