skip to Main Content

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


  1. 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.

    success: function (data, text, xhr) {  
        if(xhr.hasOwnProperty('responseJSON')){
            window.location.replace("http://addusharma.somee.com/Indent_mst/Create");
            alert("Record Save Successfully !!");            
        }
        else{
            alert("error");
            $('#form').empty();
            var result = $(data).find('#form').html();
            $('#form').html(result);
        }                  
    },
    
    Login or Signup to reply.
  2. To show the Validation Errors you need to use validation Summary in your view.

    @Html.ValidationSummary(false)

    To know further about how to use ValidationSummary read here.

    Login or Signup to reply.
  3. Controller

      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());
                }
    
                return JSON(new
                {
                    ResultStatus=false,
                    Message="Here Success Message Text...",
                    Result=new 
                    {
                        fk_sessionUserid= model.fk_sessionUserid,
                        fk_sessionLocid=model.fk_sessionLocid,
                        pk_IndentId=model.pk_IndentId,
                        Doc=model.doc
                    }
                });
    
            }
            else
            {
                return JSON(new
                {
                    ResultStatus=false,
                    Message="Here Error Text...",
                    Result=new 
                    {
                        IndentDate= DateTime.Now.ToString("dd/MM/yyyy").Replace("-", "/").ToString(),
                        GetMenuData= GetMenuByUser(),
                        GetItems=_HomeService.GetItems().ToList(),
                        IndentNo=_indent_mstService.GetAutoIndentNo(fk_locid).FirstOrDefault()
                    }
                });
            }
        }
    

    JS

        $.ajax({
        url: $('#SaveDetails').val(),
        type: "POST",
        data: JSON.stringify(data),
        dataType: "JSON",
        contentType: "application/json",
        success: function (data) {
            if(data.ResultStatus==true){
            window.location.replace("http://addusharma.somee.com/Indent_mst/Create");
            alert(data.Message);
            }else{
             alert(data.Message);       
            }
    
        },
        error: function (data) {
            alert(data.Message);
            $('#form').empty();
            var result = $(Data).find('#form').html();
            $('#form').html(result);
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search