我想在客户端验证下拉列表和列表框。
// model
public class NewStreamViewModel
{
public NewStreamViewModel()
{
this.Subjects = new List<SelectListItem>();
this.Languages = new List<SelectListItem>();
}
[Display(Name = "Language")]
[Required(ErrorMessage = "{0} is Required")]
public int LanguageId {get;set;}
[Display(Name = "Subject")]
[Required(ErrorMessage = "{0} is Required")]
public int[] SubjectIds {get;set;}
public List<SelectListItem> Languages {get;set;}
public List<SelectListItem> Subjects {get;set;}
}
//视图
<div id="tab1">
<table style="background: none; width: 100%;">
<tr>
<td>
Language
</td>
<td>
@Html.DropDownListFor(m=>m.LanguageId,Model.Languages)
@Html.ValidationMessageFor(m=>m.LanguageId)
</td>
</tr>
<tr>
<td>Stream
</td>
<td>
@Html.DropDownListFor(m => m.StreamId, Model.Streams)
</td>
</tr>
<tr>
<td>Subjects
</td>
<td>
@Html.ListBoxFor(m => m.SubjectIds, Model.Subjects,
new { Style = "width:300px;" })
@Html.ValidationMessageFor(m=>m.SubjectIds)
</td>
</tr>
</table>
<input type="button" id="addspan">
</div>
<script type="text/javascript" src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#addspan').click(function () {
var $step = $('#tab1');
var validator = $("form").validate(); // obtain validator
var anyError = false;
$step.find('select').each(function () {
// validate every input element inside this step
if (!validator.element(this)) {
anyError = true;
}
})
</script>
我使用不引人注目的验证,但它仍然不适合我, 我如何在客户端验证下拉列表和列表框?
答案 0 :(得分:0)
我的第一个猜测是jquery的脚本标记不正常。像下面的标签一样改变它:
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")"></script>
答案 1 :(得分:0)
使用hack在下拉列表中应用验证
@Html.DropDownListFor(m => m.DetailsData.TypeSelected, new SelectList(Model.Types, "Value", "Key"), "- Choose Offer Type -", new { @class = "" })
@Html.TextBoxFor(m => m.DetailsData.TypeSelected, new { @style = "visibility : hidden" })
@Html.ValidationMessageFor(m => m.DetailsData.TypeSelected, null, new { @class ="validation_arrow shift_arrow" })
@Html.ValidationMessageFor(m => m.DetailsData.TypeSelected)
答案 2 :(得分:0)
您可以执行以下操作:
$('#addspan').click(function () {
if($('#dropDownID1').val() != 0 && $('#dropDownID2').val() != 0)
//do something
else alert("Please complete required fileds");
})