0

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>
4
  • Use public IEnumerable<SelectListItem> SelectCustomers { get { return new SelectList(Customers, Customers.Id, Customers.Name); } } Commented Jun 4, 2014 at 10:24
  • @Pomster, where are you getting error Commented Jun 4, 2014 at 10:24
  • Tell me I am wrong, but as far as I know, the Type string has no Properties called Id and Name Commented Jun 4, 2014 at 10:26
  • Why does DBH.CustomerBranchGetAll(); return a list of string (and not a list of Customers / something with an Id and a Name) ? Commented Jun 4, 2014 at 10:26

2 Answers 2

2

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"))
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Correct. I bypassed the problem. This will compile for the OP though. OP has clearly followed a tutorial.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.