【问题标题】:How to show model state errors while saving data by calling ajax post如何通过调用ajax post保存数据时显示模型状态错误
【发布时间】:2020-04-16 04:25:18
【问题描述】:

我在我的操作方法中尝试的是,当模型状态无效时,我用模型数据重定向视图,但它无法在视图中显示错误

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 方法是

$.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);
    }
});

我想要实现的是,当模型状态无效时,它应该在我的视图中显示模型错误

【问题讨论】:

    标签: c# jquery ajax asp.net-mvc model-view-controller


    【解决方案1】:

    Ajax error 函数只有在请求失败时才会启动。在您的情况下,控制器在两种情况下都返回成功结果。所以你需要在 success 函数中处理所有事情。

    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);
        }                  
    },
    

    【讨论】:

      【解决方案2】:

      要显示验证错误,您需要在视图中使用验证摘要。

      @Html.ValidationSummary(false)

      要进一步了解如何使用 ValidationSummary,请阅读here

      【讨论】:

        【解决方案3】:

        控制器

          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);
            }
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-08
          • 2023-03-25
          • 2012-10-29
          • 1970-01-01
          • 1970-01-01
          • 2016-11-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多