user1435266
user1435266

Reputation:

Populate a dropdownlist in MVC3 not working

I am learning MVC3 and I can't find a way that works to populate a dropdown list. Tried examples from StackOverFlow, not working. Tried from a project that I found on the web and that doesn't work. Found this guy's tutorial on Youtube it gives me the following error:

There is no ViewData item of type 'IEnumerable' that has the key 'Categ'.

And now I am out of options.

This is where I get the values in a list(I think):

public class Cat
{
    DataBaseContext db;

    public IEnumerable<MyCategory> Categories()
    {
        db = new DataBaseContext();
        List<MyCategory> categories = (from b in db.BookCategory
                                       select new MyCategory { name = b.Name, id = b.ID }).ToList();

        if (categories != null)
        {
            var ocategories = from ct in categories
                              orderby ct.id
                              select ct;
            return ocategories;
        }
        else return null;

    }
}

public class MyCategory
{
    public string name { get; set; }
    public int id { get;set;}
}

This is the Controller:

// GET: /Entity/Create

    public ActionResult Create()
    {
        return View();
    }


 [HttpPost]
    public ActionResult Create(BookEntity ent)
    {
        Cat ca= new Cat();

        IEnumerable<SelectListItem> items = ca.Categories().Select(c => new SelectListItem
        {
            Text = c.name,
            Value = c.id.ToString()
        });
        ViewBag.Categ = items;


        db.BookEntity.Add(ent);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

And this is the View:

<div class="editor-field">
        @Html.DropDownList("Categ"," Select One ")

    </div>

Somehow it doesn't work for me. I appreciate any help and advice.

Upvotes: 0

Views: 246

Answers (1)

heads5150
heads5150

Reputation: 7443

Modify your action method to use ViewData instead of ViewBag and the View mark up will work.

public ActionResult Create()
    {
        Cat ca= new Cat();

        IEnumerable<SelectListItem> items = ca.Categories().Select(c => new SelectListItem
        {
            Text = c.name,
            Value = c.id.ToString()
        });
        ViewData["Categ"] = items;

        return View("Index");
    }

[HttpPost]
public ActionResult Create(BookEntity ent)
    {   
        db.BookEntity.Add(ent);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

You need to populate the ViewData in the GET action not the POST action. By naming the dropdown list Categ as well MVC conventions will automagically look in the ViewData container.

Upvotes: 1

Related Questions