我正在开发MVC应用程序。
我在Creat-Veiw中使用Jquery来验证数据。
我有一个接受角色的文本框,在模糊函数上,我检查了角色是否已经存在。
一切正常,如果角色已经存在,那么验证消息就会出现。但在点击保存按钮后,它会保存在数据库中。
我想阻止它吗?该怎么做呢?
我有下面的代码创建视图。
    @model IEnumerable<PaymentAdviceEntity.Role>
    <div id="roleList">
    <div class="span6">
    <div class="span12 HeaderField2">
        Roles
    <legend style="margin-bottom:2px;margin-top:5px;"></legend>
    </div>
    <div  class="span12">    
        <div style="display:inline-block"></div>
        <div id="addrole" style="display:none">
        <span> @Html.TextBox("RoleName", String.Empty, new { @id = "RoleName",style="margin-bottom:0px;" })</span>
           <span> 
               <input type="button" value="Save" id="btnSave"/>
                <input type="button"  value="Cancel" id="btnCancel" />
           </span>
      </div>    
        <div style="margin-top:5px;">
 <span id="RoleNameValidation" style="display:none;color:Red;">Role already exists</span>
        </div>
    </div>
    </div>为此,我使用下面的Jquery。
 $("#RoleName").blur(function ()
    {
        var Role_Name = $('#RoleName').val();
        //alert(RoleName);
        var url = "@Html.Raw(Url.Action("checkForUniqueName","Role",new {@RName = "RoleName"}))";
        url = url.replace("RoleName", Role_Name);
        $.post(url, function (data)
        {
            if (data == false) {
                $("#RoleNameValidation").show();
                $('#RoleName').focus();
            }
            else {
                $("#RoleNameValidation").hide()
            }
        });
    });控制器代码是....
 public ActionResult checkForUniqueName(string RName)
         {
            bool Valid = false;
            var RoleList = from e in db.Roles
                           where e.Name.Equals(RName)
                           select e;
            if (RoleList.Count() > 0 )  
            {
                Valid = false;
            }
            else
            {
                Valid = true;
            }
            return Json(Valid, JsonRequestBehavior.AllowGet);
         }发布于 2013-03-16 14:42:22
如果不想在数据库中插入重复记录,则可以使用验证。
尝试使用jQuery验证插件(使用addMethod)创建自定义规则,该插件检查角色在database.You中是否已经存在可以在http://matthewmuro.com/2012/05/08/adding-custom-jquery-validation-to-your-form/上找到很好的帮助
https://stackoverflow.com/questions/15446312
复制相似问题