I'm trying to make a validation for my dropdownlist in MVC5 that user must select an item but I'm not sure how to do it. I've created my list inside the Model class for some reason and now I don't know how to apply [Require(ErrorMessage)]
to this program
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>
Model:
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;
}
it has an error when I apply [Require()]
error image
You need to store the value of your DD in a variable like follows:
[Required(Errormessage="message")] // just add this in your model
public string Project_Type {get;set;}
And change your List
like follows:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.