如何使用DataAnnotation验证dropdownlist? [英] how to validate dropdownlist using the DataAnnotation?
问题描述
我需要您的帮助,我在使用AdataAnnotation进行验证时遇到了问题
I need your help, I have a problem with the validation using AdataAnnotation
我正在尝试使用它来验证下拉列表,但是存在一些问题
I am trying to validate a dropdown list using it but there is some problem with it
这是我的代码
查看侧
@using (Html.BeginForm("addNewProject", "Activities", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationMessage("ProjectName")
<h3>Project Name: </h3>
@Html.TextBox("ProjectName", null, new { @class = "text_field"} )
@Html.ValidationMessage("ProjectOwner")
<h3>Project Owner: </h3>
@Html.DropDownList("ProjectOwner", (SelectList)ViewBag.Customers, new { @class = "text_field" })
@Html.ValidationMessage("Description")
<h3>Description: </h3>
@Html.TextArea("Description", new { @class = "text_area"})
@Html.ValidationMessage("Department")
<h3>Departments: </h3>
@Html.DropDownList("Department", (SelectList)ViewBag.Departments, new { @class = "list" })
@Html.ValidationMessage("Region")
<h3>Regions: </h3>
@Html.DropDownList("Region", (SelectList)ViewBag.Regions, new { @class = "list" })
<input type="submit" value="Add" class="submit" />
}
控制器端
public ActionResult NewProject()
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem() { Value = "0", Text = "Choose ..." });
list.Add(new SelectListItem() { Value = "1", Text = "First" });
list.Add(new SelectListItem() { Value = "2", Text = "Second" });
list.Add(new SelectListItem() { Value = "3", Text = "Third" });
ViewBag.Departments = new SelectList(list, "Value", "Text");
ViewBag.Regions = new SelectList(list, "Value", "Text");
ViewBag.Customers = new SelectList(list, "Value", "Text");
return View();
}
public ActionResult addNewProject(Project newProject)
{
if (ModelState.IsValid)
{
return RedirectToAction("index", "Home");
}
else
{
return View("NewProject", newProject);
}
}
数据持有人
The Data Holder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace workflow.DataHolders
{
public class Project : DataHolder
{
[Required(ErrorMessage = "This Field Is Required")]
[StringLength(200, MinimumLength = 3, ErrorMessage = "Length Of The Title Should Be More Than 3 Letters")]
public string ProjectName{ get; set; }
[Required(ErrorMessage = "This Field Is Required")]
public List<SelectListItem> ProjectOwner { get; set; }
string Description { get; set; }
[Required(ErrorMessage = "This Field Is Required")]
public List<SelectListItem> Department { get; set; }
[Required(ErrorMessage = "This Field Is Required")]
public List<SelectListItem> Region { get; set; }
}
}
推荐答案
您的代码有2个主要问题.
There are 2 main issues with you code.
首先,您尝试将<select>
绑定到List<SelectListItem>
的属性,但是<select>
仅回发无法绑定到List<SelectListItem>
的单个值类型,因此该属性是null
验证失败.您的属性必须是(例如)typeof int
或string
.
First your trying to bind a <select>
to a property which is List<SelectListItem>
, but a <select>
only posts back a single value type which can't be bound to List<SelectListItem>
so the property is null
and validation fails. Your properties need to be (for example) typeof int
or string
.
第二,您手动添加带有Value ="0"
和Text = "Choose ..."
的SelectListItem
,这意味着即使更正了第一个问题,如果用户选择了第一个选项(选择..."),您的模型也会之所以有效,是因为"0"是有效值.
Secondly, your manually adding a SelectListItem
with Value ="0"
and Text = "Choose ..."
which means that even if you correct the first issue, if the user selects the first option ("Choose ..."), your model will be valid because "0" is a valid value.
您的课程必须是
public class Project : DataHolder
{
....
[Display(Name = "Project Owner")]
[Required(ErrorMessage = "Please select a project owner")]
public int ProjectOwner { get; set; }
public List<SelectListItem> ProjectOwnerList { get; set; }
.... // ditto for Department and Region
}
然后在控制器中
public ActionResult NewProject()
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem() { Value = "1", Text = "First" });
list.Add(new SelectListItem() { Value = "2", Text = "Second" });
list.Add(new SelectListItem() { Value = "3", Text = "Third" });
// Initialize the model
Project model = new Project();
model.ProjectOwnerList = list;
model.DepartmentList = list;
model.RegionList = list;
return View(model); // always return a model even if its just a default new instance!
}
请注意,您的模型包含List<SelectListItem>
的属性,因此请勿使用ViewBag
,并且在任何情况下,DropDownList()
方法仅需要IEnumerable<SelectListItem>
作为其第二个参数,因此可以从<创建新的SelectList
c1>只是不必要的额外开销
Note your model contains properties for List<SelectListItem>
so don't use ViewBag
, and in any case, the DropDownList()
method only requires IEnumerable<SelectListItem>
as its second parameter, so creating a new SelectList
from List<SelectListItem>
is just unnecessary extra overhead
然后在视图中
@Html.LabelFor(m => m.ProjectOwner)
@Html.DropDownListFor(m => m.ProjectOwner, Model.ProjectOwnerList, "Choose...")
@Html.ValidationMessageFor(m => m.ProjectOwner)
请注意,DropDownListFor()
的第三个参数会添加一个带有null
值的labelOption
-<option value>Choose...</option>
-,因此,如果选择了该参数,您现在将收到一条错误消息,并且该模型将无效.
Note that the 3rd parameter of DropDownListFor()
adds a labelOption
with a null
value - <option value>Choose...</option>
-, so if its selected, youu will now get an error message and the model will be invalid.
假设用户选择"Second"
,那么当您发回邮件时,ProjectOwner
的值将为2
.
Assuming the user selects "Second"
, then when you post back, the value of ProjectOwner
will be 2
.
这篇关于如何使用DataAnnotation验证dropdownlist?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!