Search code examples
c#asp.net-mvcdropdownlistfor

How to add a MVC Dropdownfor list<string>


I am trying to add a Dropdownlistfor to my MVC Project with no luck. I would like to display a list of customers. I would like the customers displayed and the ID selected.

I am struggling with casting my list into the selectListItems, Could someone please help me out with this.

Controller

public ActionResult createNewUser()
{

    List<string> Customers = DBH.CustomerBranchGetAll();

    var Model = new UserModel
    {
       Customers = Customers
    };

    return View(Model);

}

Model

public class UserModel
{

   public int CustomerId { get; set; }
   public List<string> Customers { get; set; }
   public IEnumerable<SelectListItem> SelectCustomers
   {
      get { return new SelectList(Customers, "Id", "Name"); }
   }
}

View

<div class="editor-label">
    @Html.Label("Choose Your Customer name")
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.CustomerId, Model.SelectCustomers)
    @Html.ValidationMessageFor(model => model.Customers)
</div>

Solution

  • Read SelectList

    Your Customers is not an object which contains Id & Name properties. In your code it is just a list of string.List<string> Customers

    You need to define an class with Name and Id properties and make use of it

    public class Customer{
     public string Name{get;set;}
     public int Id {get;set;}
    }
    

    Then prepare a customer object with Id and Name property assigned

    List<Customers> customers = DBH.CustomerBranchGetAll(); 
    var Model = new UserModel
    {
       Customers = customers
    };
    

    In View

      @Html.DropDownListFor(model => model.CustomerId, 
                            new SelectList(Model.Customers,"Id","Name"))