如何使用jQuery在AJAX调用中调用MVC服务器端验证



html

<div class="portlet-body"> @using (Html.BeginForm()) { @Html.AntiForgeryToken()
  <div class="form-horizontal">
    <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group"> @Html.LabelFor(model => model.Details, htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10"> @Html.EditorFor(model => model.Details, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Details, "", new { @class = "text-danger" }) </div>
    </div>
    <div class="form-group">
      <div class="col-md-offset-2 col-md-10">
        <input type="button" onclick="MainSave()" value="Create" class="btn btn-primary" /> </div>
    </div>
  </div> } </div> 

Java脚本jQuery

var MainSave = function() {
  var Geturl = $("#hidUrlofsave").val();
  var Details = $("#Details").val();
  var Id = $("#hidid").val();
  if (Details != "") {
    $.ajax({
      url: Geturl,
      type: "Post",
      data: {
        Details: Details,
        Id: Id
      },
      success: function(res) {
        if (res == "true") {
          Loaditem();
          AutoLoader("Save", "success");
          $("#Details").val("");
        } else if (res == "update") {
          Loaditem();
          AutoLoader("Update", "success");
          $("#hidid").val("");
        } else {
          AutoLoader("error", "error");
        }
      }
    })
  } else {
    $("#Details").css("border", "solid 1px red")
  }
}

c敏锐的MVC动作代码

[HttpPost] 
public string ErpMainItem(tbl_inv_Main main) {
      try {
        if (main.Id == 0) {
          var ad = new MainRepoistory().Add(main);
          if (ad) {
            return "true";
          } else {
            return "false";
          }
        } else {
          var ad = new MainRepoistory().Update(main);
          if (ad) {
            return "update";
          } else {
            return "false";
          }
        }
      } catch (Exception e) {
        return "false";
      }
    }

您不能仅调用使用Ajax在服务器端编写的验证,而这样做也不是一个好方法。

您可以在发布表单时验证模型

//Check if posted model data is valid or not
//checks every validation data annotation
if(ModelState.IsValid)
{
  //<Model is valid
}

对于客户端的相同效果(验证),您必须包括3个文件

  1. jquery.js
  2. jquery.validate.js
  3. jquery.validate.unobtrusive.js

您可以使用上述文件的缩小版本,但应维护序列。在执行客户端验证之后,无需将数据发送到服务器。您将获得您在服务器端编写的所有验证规则。像必需 maxlength email etc et eq for HTML元素绑定到模型属性。

@Html.TextBoxFor(m=>m.Email, new{@class="form-control"}

更新

如果数据是通过ajax发布的,并且按钮不是提交类型的类型,则可以使用.valid()函数验证表单。

$("#postMyData").on('click', function(e){
   var isFormValid = $("#myForm").valid();
   if(isFormValid)
   {
    //Ajax Call
   }
});

最新更新