Pillowsky
Pillowsky

Reputation: 9

MVC5 dropdownlist validation

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

enter image description here

Upvotes: 0

Views: 81

Answers (1)

Kiran Joshi
Kiran Joshi

Reputation: 1876

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

Upvotes: 2

Related Questions