Pomster
Pomster

Reputation: 15197

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>

Upvotes: 0

Views: 142

Answers (2)

Murali Murugesan
Murali Murugesan

Reputation: 22619

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"))

Upvotes: 2

Simon Whitehead
Simon Whitehead

Reputation: 65049

SelectList has a constructor that takes an IEnumerable.. so you just need to do this:

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

You can remove the SelectCustomers property entirely.

Upvotes: 1

Related Questions