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-selectpicker
和textbox
(即strongly typed
和viewmodel
)定制的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插件隐藏了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 ID
和string 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