Nikhil Jog
Nikhil Jog

Reputation: 41

MVC3 - DropDownListFor not populating

I have tried for the entire day but the drop down,list I have fails to load. Its supposed to be a simple application. I need to create a new Employee, while the create view renders I a dropdownlist populated with different [Store Names] from a StoresMst table. The idea is to associate an employee with a store. Below is my code

In the viewModel Class

    public class EmployeeStoreViewModel
    {
        private JCOperationsDataContext  db = new JCOperationsDataContext ();

        //public Employee employee { get; set; }
        public IEnumerable<SelectListItem> Stores { get;set;}
        public int storeID { get; set; }         
    }

In the Create ActionLink

        public ActionResult Create()
        {
            //ViewData["PartialStores"] = repository.GetStoreNames();
            var model = new EmployeeStoreViewModel()
            {   
                //Stores= jc.StoreMsts.OrderBy(o=> o.StoreID).ToList<SelectListItem>();

                Stores = jc.StoreMsts
                        .ToList()
                        .Select(x => new SelectListItem
                        {
                            Text = x.StoreID.ToString(),
                            Value = x.StoreName
                        }),                        
            };

            return View(model);
        }

In the View (added a reference to ModelView Class

<div class="editor-field">
    @{Html.DropDownListFor(model => model.storeID, new SelectList (Model.Stores));}
</div >

The page loads without an error but no DropDownbox is rendered and populated. Am I missing anything? I am using MVC3 with VS2010 Ultimate Just a note: I tried the same with MVC2 and that did work.

Upvotes: 1

Views: 278

Answers (2)

Eric Garrison
Eric Garrison

Reputation: 360

Because you have your Stores object in your view model, and you're setting that collection before passing it in, you don't need to use a "new SelectList", you can just reference that property in the collection. Also, you don't need the curly braces around your drop list, it will not evaluate that way. This should be all you need:

<div class="editor-field">
@Html.DropDownListFor(model => model.storeID, Model.Stores);
</div >

Edit: After looking at your code again, if your drop down list doesn't load this way, you may need to change the collection type to a List instead of IEnumerable.

Upvotes: 0

Eranga
Eranga

Reputation: 32437

Remove the curly braces in DropDownListFor call. In your code razor treats it as a regular method call and neglects the return value of the method. The correct syntax to output html using razor is as follows.

<div class="editor-field">
    @Html.DropDownListFor(model => model.storeID, new SelectList (Model.Stores))
</div >

Upvotes: 2

Related Questions