客户端验证无效

时间:2013-02-18 18:51:04

标签: jquery asp.net-mvc-4 jquery-validate unobtrusive-validation

我实施了客户端验证,即attributesModel中指定的必需HTMLValidationMesssage适用于.cshtml并引用了JQuery验证工具,点击save button时工作正常。但是当我实现按钮的onClick event和ajax调用时,验证似乎无效。我尝试使用IsValid但没有运气。

请找到以下代码。

控制器

  [HttpPost]
        public ActionResult AddClient(ClientModel clientData)
        {
            var clientObj = new Metadata.Client.Service.Client();

            string successMessage = string.Empty;

            clientObj.ClientType              = new Metadata.Client.Service.ClientType();
            clientObj.ClientName              = clientData.Client.ClientName;
            clientObj.ClientCode              = clientData.Client.ClientCode;
            clientObj.ClientType.ClientTypeId = clientData.ClientTypeSelectId;

             try
             {
                 clientObj = clientData.AddNewClient(clientObj);
             }
             catch (Exception ex)
             {

                  return new ContentResult { Content = ex.Message, ContentType = "application/json" };

             }

             return new ContentResult { Content = successMessage, ContentType = "application/json" };
             //return RedirectToAction("Index");

        }

JQuery - 添加了以下参考资料。

<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js" type="text/javascript"></script>
 $("#addForm").validate(
    {


        submitHandler: function (form) 
        {
                var clientName = $('#Client_ClientName').val();
                var clientTypeId = $('#ClientTypeSelectId').val();
                var clientCode = $('#Client_ClientCode').val();

           $.ajax({
                    type: "POST",
                    async: false,
                    url: "/Client/AddClient",
                    cache: false,
                    data: { "clientName": clientName, "clientTypeId": clientTypeId, "clientCode": clientCode },
                    dataType: "json",
                    error: function (request) {
                        alert(request.responseText);
                    },
                    success: function (result) {
                        //alert('Successfully Inserted Client');
                        $.ajax({
                            url: "/Client/ClientGrid",
                            type: 'GET',
                            datatype: 'json',
                            success: function (data) {
                                $('#grid').html(data);
                                //alert('got here with data');
                            },
                            error: function () {
                                //alert('something bad happened');
                            }
                        });

                        $('#myClientDialogContainer').dialog('close');
                    }
                });
                return false;
            }
        });

模型

   public class Client
    {
        public int ClientId { get; set; }

        [Required(ErrorMessage = "Please Enter Client Name")]
        [Display(Name = "Client Name")]
        public string ClientName { get; set; }

        public ClientType ClientType { get; set; }
        public StatusType StatusType { get; set; }

        //[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [Required(ErrorMessage = "Please Enter Client Code")]
        [DataType(DataType.Text)]
        [Display(Name = "Client Code")]
        public string ClientCode { get; set; }

        //[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Text)]
        [Display(Name = "Client Status Type Name")]
        public string ClientStatusTypeName { get; set; }

        //[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Text)]
        [Display(Name = "Client Status Code Name")]
        public string ClientStatusCodeName { get; set; }

        [Display(Name = "Client Type Id")]
        public int ClientTypeId { get; set; }
    }

验证码

<div class="editor-field">
    <span>

        @Html.ValidationMessageFor(c => c.Client.ClientName)
        <div class="row"></div>
        <span class ="label"> @Html.LabelFor(c => c.Client.ClientName, "Client Name :")</span>
        @Html.TextBoxFor(c => c.Client.ClientName, new { style = "width:50%; height:20px;" })
    </span>
    </div>
    <div class="editor-field">
        <span>
             @Html.ValidationMessageFor(m => m.ClientTypeSelectId)
             <div class="row"></div>
            <span class ="label">@Html.LabelFor(m => Model.Client.ClientType.ClientTypeName, "Client Type :")</span>
             @Html.DropDownListFor(m => m.ClientTypeSelectId, (SelectList)ViewBag.clientTypeListCombo, " ", new { style = "width:52%" })


        </span>
    </div>
    <div class="editor-label">
        <span>
            @Html.ValidationMessageFor(m => m.Client.ClientCode)
            <div class="row"></div>
            <span class="label">@Html.LabelFor(m => m.Client.ClientCode, "Client Code :")</span>
            @Html.TextBoxFor(m => m.Client.ClientCode, new { style = "width:50%; height:20px;" })
        </span> 
    </div>

请任何人帮忙。

1 个答案:

答案 0 :(得分:1)

不要在单击按钮时提交表单,而是尝试表单的.submit()事件。将输入元素包装在html表单标记内。您应该序列化表单并将其提交给服务器,而不是逐个获取输入值。

$('#myForm').submit(function (e) {

   // Prevent default submit for ajax
   e.preventDefault();

   $.ajax({ /* Your ajax stuff goes here */ });
});

这样您就不会绕过验证。