MVC5下拉列表验证

时间:2018-08-16 09:04:55

标签: c# asp.net-mvc asp.net-mvc-5

我正在尝试对MVC5中的下拉列表进行验证,即用户必须选择一个项目,但是我不确定该怎么做。由于某种原因,我已经在Model类中创建了列表,但现在我不知道如何将[Require(ErrorMessage)]应用于该程序

cshtml:

<label>Project Type:</label>
     @Html.DropDownListFor(m => m.Project_Type, Project1.Models.Dropdowns.GetProjectType(), "--Project Type--", new { @class = "form-control" })
    <h6 style="text-emphasis-color:red;text-decoration-color:red" class="error"> @Html.ValidationMessageFor(model => model.Project_Type)</h6>

型号:

   public static IEnumerable<SelectListItem> GetProjectType()
    {

    List<SelectListItem> Project_Type = new List<SelectListItem>();

    Project_Type.Add(new SelectListItem() { Text = "type1" });
    Project_Type.Add(new SelectListItem() { Text = "type2" });
    Project_Type.Add(new SelectListItem() { Text = "type3" });
    Project_Type.Add(new SelectListItem() { Text = "type4" });

    return Project_Type;
    }

应用[Require()]时出现错误

  

错误图片

enter image description here

1 个答案:

答案 0 :(得分:2)

您需要将DD的值存储在如下变量中:

[Required(Errormessage="message")] // just add this in your model
public string Project_Type {get;set;}

并按如下所示更改您的List

public static IEnumerable<SelectListItem> GetProjectType()
{

    List<SelectListItem> Project_Type = new List<SelectListItem>();
    Project_Type.Add(new SelectListItem() { Text = "type1",value="1" });
    Project_Type.Add(new SelectListItem() { Text = "type2",value="2" });
    Project_Type.Add(new SelectListItem() { Text = "type3",value="3" });
    Project_Type.Add(new SelectListItem() { Text = "type4",value="4"});

    return Project_Type;
}