Mr A
Mr A

Reputation: 6778

Simple Validation for dropdownlist in mvc using (Html.ValidationMessage)

Controller

var productList = Enumerable.Range(1, 80).Select(
    x => new SelectListItem { Value = x.ToString(), Text = x.ToString() }
);
ViewData["products"] = new SelectList(productList.ToList(), "Value", "Text");

View

<%: Html.DropDownList("products", ViewData["products"] as SelectList, "--select--")%>
<%: Html.ValidationMessage("products", "Please Select the Product from the List")%> 
//This doesnt works on (ModelState.IsValid) I know the dropdown list data is coming
//from the view data not model , thats why model doesnt validate the particular dropdown 
//list while it validates other fields which are linked to model,
//Just want to know, how can i validate the above dropdownlist 

Upvotes: 2

Views: 11294

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039488

You are binding both the name of the ddl and the values to products. That's wrong. Of course that's the least problem with your code. The far bigger and more serious problem is that you are using ViewData instead of using strongly typed views and view models.

So there are two possibilities:

  1. The crappy one: have a property on your view model to which you will bind your dropdown value.

    [Required(ErrorMessage = "Please Select the Product from the List")]
    public string SelectedProduct { get; set; }
    

    and then use this property name as first argument to the weakly typed DropDownList helper and the ViewData as second agrument:

    <%= Html.DropDownList( 
        "SelectedProduct", 
        ViewData["products"] as SelectList, 
        "--select--"
    ) %>
    <%= Html.ValidationMessage("SelectedProduct") %>
    
  2. The correct way: which of course is using real view models (I am sick of repeating it, just google, you will get like gazillions of answers, just by me, and just on this site on this topic). It will look like this:

    <%: Html.DropDownListFor( 
        x => x.SelectedProduct, 
        Model.Products, 
        "--select--"
    ) %>
    <%= Html.ValidationMessageFor(x => x.SelectedProduct) %>
    

Upvotes: 11

Related Questions