不工作的客户端验证 [英] Client side validation not working

查看:105
本文介绍了不工作的客户端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了客户端验证即要求属性模型指定 HTML ValidationMesssage 对于 .cshtml ,并参考了 JQuery的验证并工作正常,当我在点击保存按钮。但是,当我执行 onClick事件按钮 Ajax调用,验证似乎不工作。我试着用的IsValid ,但没有运气。

I implemented client side validation i.e, Required attributes specified in Model and HTML.ValidationMesssage For in .cshtml and referenced the JQuery validator and was working fine when I click on save button. But when I implement onClick event of button an ajax call, the validation seems to be not working. I tried using IsValid but no luck.

请找到低于code。

控制器

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

验证code

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

请谁能帮助。

推荐答案

相反被点击按钮时提交表单,尽量.submit()窗体的事件。总结HTML表单标签中的输入元素。你应该序列化的形式和一个提交到服务器,而不是采取输入值之一。

Instead of submitting your form when button is clicked, try .submit() event of your form. Wrap your input elements inside html form tag. You should serialize your form and submit it to server instead of taking input values one by one.

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

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

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

此方式,您将无法绕过您的验证。

This way you won't bypass your validation.

这篇关于不工作的客户端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆