我需要您的帮助,使用AdataAnnotation进行验证时遇到问题

我正在尝试使用它来验证下拉列表,但是它有一些问题

这是我的代码


查看侧


        @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);
        }
    }



数据持有人


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个主要问题。

首先,您尝试将<select>绑定到List<SelectListItem>的属性,但是<select>仅回发无法绑定到List<SelectListItem>的单个值类型,因此该属性是null并且验证失败。您的属性必须是(例如)typeof intstring

其次,您手动添加带有SelectListItemValue ="0"Text = "Choose ...",这意味着即使更正了第一个问题,如果用户选择了第一个选项(“选择...”),您的模型也将有效,因为“ 0”是有效值。

您的课程需要

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创建新的List<SelectListItem>是只是不必要的额外开销

然后在视图中

@Html.LabelFor(m => m.ProjectOwner)
@Html.DropDownListFor(m => m.ProjectOwner, Model.ProjectOwnerList, "Choose...")
@Html.ValidationMessageFor(m => m.ProjectOwner)


请注意,DropDownListFor()的第三个参数会添加一个带有labelOption值-null-的<option value>Choose...</option>,因此,如果选择了该参数,则您将收到一条错误消息,并且该模型将无效。

假设用户选择"Second",那么当您发回邮件时,ProjectOwner的值将为2

关于asp.net-mvc-4 - 如何使用DataAnnotation验证dropdownlist?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31099817/

10-13 07:55