我在asp .net mvc3 c#中创建一个应用程序。我创建了一个下拉列表,但我无法使用Jquery进行客户端验证。
我查看过很多与之相关的文章,并且知道这是asp .net mvc3中的一个错误。但是,没有任何工作可以解决我的问题。
我的代码如下:
实体
[Required(ErrorMessage = "Furnishing is required.")]
[Display(Name = "Furnishing*")]
public int FurnishedType { get; set; }
查看:
<script src="@Url.Content("~/Scripts/jquery-1.8.2.js")" type="text/javascript"></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>
<div class="editor-label">
@Html.LabelFor(model => model.Property.FurnishedType)
@Html.DropDownListFor(model => model.Property.FurnishedType, Model.FurnishedTypes, "--Select One--")
</div>
<div class="editor-field add-property-error">
@Html.ValidationMessageFor(model => model.Property.FurnishedType)
</div>
控制器:
public ActionResult AddProperty()
{
AddPropertyViewModel viewModel = new AddPropertyViewModel
{
...
FurnishedTypes = websiteRepository.GetFurnishedTypeSelectList(-1),
...
};
return View(viewModel);
}
public IEnumerable<SelectListItem> GetFurnishedTypeSelectList(int selectedId)
{
return db.FurnishedType
.OrderBy(x => x.FurnishedTypeDescription)
.ToList()
.Select(x => new SelectListItem
{
Value = x.FurnishedTypeId.ToString(),
Text = x.FurnishedTypeDescription
});
}
有一个数据库,其值如下
1 Furnished
2 Part Furnished
...
用于填充选择列表。
现在,这是必填字段,但我无法进行客户端验证以查看用户是否选择了任何值? 任何帮助都会感激不尽
答案 0 :(得分:0)
如果您将-1分配给“ - 选择一个 - ”
有些东西应该是这样的:
$(document).ready(function () {
$("input[type='submit']").click(function (e) {
if($("select").val()==="-1"){
e.preventDefault();
// display error msg beside ddl too
}
});
}
)
答案 1 :(得分:0)
我的建议是做以下
在视图中
@using (Html.BeginForm("AddProperty", "Home", FormMethod.Post, new { id = "myForm" }))
{
<div class="editor-label">
@Html.LabelFor(model => model.Property.FurnishedType)
@Html.DropDownListFor(model => model.Property.FurnishedType, Model.FurnishedTypes)
</div>
<div class="editor-field add-property-error">
@Html.ValidationMessageFor(model => model.Property.FurnishedType)
</div>
}
<script type="text/javascript">
$.validator.addMethod('selectNone', function (value, element) {
return this.optional(element) || value != -1;
}, "Furnishing is required.");
$("#myForm").validate({
rules: { FurnishedType: { selectNone: true }}
});
</script>
在控制器
中public IEnumerable<SelectListItem> GetFurnishedTypeSelectList(int selectedId)
{
List<SelectListItem> Lists = new List<SelectListItem>();
Lists = db.FurnishedType
.OrderBy(x => x.FurnishedTypeDescription)
.ToList()
.Select(x => new SelectListItem
{
Value = x.FurnishedTypeId.ToString(),
Text = x.FurnishedTypeDescription
});
Lists.Insert(0, new SelectListItem { Text = "--Select One--", Value = "-1" });
return Lists;
}