what i have tried in my action method is when the model state is not valid i redirect the view with the model data but it could not show the errors in view
public ActionResult Create(IndentmstViewData model)
{
model.fk_sessionUserid = Session["userID"].ToString();
model.fk_sessionLocid = Session["fk_locid"].ToString();
model.pk_IndentId = Convert.ToInt32(TempData["EditId"]);
if (ModelState.IsValid)
{
XDocument doc = new XDocument(new XDeclaration("1.0", "UTF - 8", "yes"),
new XElement("XMLdata",
from itemdet in model.GetItemDetails
select new XElement("ItemDetails",
new XElement("fk_itemid", itemdet.fk_ItemId),
new XElement("qty", itemdet.Qty),
new XElement("balqty", itemdet.indbalqty),
new XElement("estimatedcost", itemdet.EstimatedCost),
new XElement("partno", itemdet.PartNo),
new XElement("itemdesc", itemdet.itemDesc),
new XElement("fk_indentid", model.pk_IndentId))));
model.doc = doc.ToString();
if (model.pk_IndentId == 0)
{
_indent_mstService.Save(model.ADTO());
}
else
{
_indent_mstService.Update(model.ADTO());
}
}
else
{
string fk_locid = Session["fk_locid"].ToString();
model.IndentDate = DateTime.Now.ToString("dd/MM/yyyy").Replace("-", "/").ToString();
model.GetMenuData = GetMenuByUser();
model.GetItems = _HomeService.GetItems().ToList();
model.IndentNo = _indent_mstService.GetAutoIndentNo(fk_locid).FirstOrDefault();
return View(model);
}
return Json(model, JsonRequestBehavior.AllowGet);
}
jQuery Ajax Post method is
$.ajax({
url: $('#SaveDetails').val(),
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",
success: function (data) {
window.location.replace("http://addusharma.somee.com/Indent_mst/Create");
alert("Record Save Successfully !!");
},
error: function (data) {
alert("error");
$('#form').empty();
var result = $(Data).find('#form').html();
$('#form').html(result);
}
});
what i want to achieve is, when model state is not valid it should show the model errors in my view
3
Answers
Ajax error function will be launched only if request failed. In your case controller returns success result in both cases. So you need to handle everything in success function.
To show the Validation Errors you need to use validation Summary in your view.
To know further about how to use ValidationSummary read here.