jquery validate on @Html.DropDownListFor with bootstrap sele

本文关键字:with bootstrap sele DropDownListFor @Html validate on jquery | 更新日期: 2023-09-27 18:12:11

我有一个form,其中说我有2个控件。使用bootstrap-selectpickertextbox(即strongly typedviewmodel)定制的select控制器。下面是项目结构的细节,这里是DEMO,验证使用的是jquery-validate

SampleViewModel.cs

public class SampleViewModel
{
        [Required(ErrorMessage="Please Select a Role")]
        //Not sure whether Required has to be assigned to RoleId or Roles
        public int RoleId { get; set; }
        public SelectList Roles { get; set; }
        [Required(ErrorMessage="Please Enter a name")]
        public string name{get;set;}
}
<<p> 视图/strong>
<div class="container">
    <div class="col-md-6 col-md-offset-3">
        <h1>Hello Stranger</h1>
            @using (Html.BeginForm("", "", FormMethod.Post, 
                             new { enctype = "multipart/form-data", id="frmSample" }))
            {
                <div class="form-group">
                    @Html.DropDownListFor(m => m.RoleId, Model.Roles, "Please Select your Country", new{@class="selectpicker"})
                    @Html.ValidationMessageFor(m=>m.RoleId)
                </div>
                <div class="form-group">
                    @Html.TextBoxFor(m => m.name, null, new{@class="form-control"}) 
                    @Html.ValidationMessageFor(m=>m.name)
                </div>
                <button type="button" class="btn btn-success submit">Ask</button>
            }
            <br/><br/>
        </div>
</div>
控制器

public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        SampleViewModel model=new SampleViewModel();
        model.Roles = new SelectList(new string[] { "Admin", "Manager" });
        return View(model);
    }
}

JS

$(document).ready(function(){
    $('.selectpicker').selectpicker();
    $("#frmSample").validate({
        onfocusout: true
    });
});
$('.submit').on('click',function(){
    if($("#frmSample").valid())
        alert(true);
});

  • 我面临的问题是我的dropdown元素没有得到使用jquery validation验证,而我的textbox得到验证。可能是我初始化的方式有问题将Required属性赋值给特定的model属性,我不确定哪一个分配required属性。
  • 我已经给onfocusout:true验证焦点,但除非你在textbox上输入一些东西,然后删除内容验证不发生

jquery validate on @Html.DropDownListFor with bootstrap sele

您的jquery插件隐藏了DropDownListFor()方法生成的<select>元素(display:none;)并添加了自己的html。默认情况下,jquery.validate.js不验证隐藏输入,因此需要使用

覆盖此行为
$.validator.setDefaults({ 
  ignore: []
});

注意这将验证所有隐藏的输入所以要验证这个输入,你可以使用ignore: ":hidden:not('#RoleId')"

此外,您还有其他错误。你的RoleId属性的类型是int,但你的SelectList将生成选项的值是strings("Admin"answers"Manager"),不能绑定到int。要么将属性更改为string RoleId,要么使用类型为int的值创建SelectList。例如,如果您有一个Roles表,其中包含字段int IDstring Name,则

var roles = db.Roles();
model.Roles = new SelectList(roles, "ID", "Name");

model.Roles = roles.Select(r => new SelectListItem()
{
  Value = r.ID.ToString(),
  Text = r.Name
};

引用DotNetFiddle