2013-01-15 51 views
0

我正在学习MVC3,我无法找到一种方法来填充下拉列表。 尝试从StackOverFlow中的示例,无法正常工作。从我在网络上找到的一个项目尝试,并且不起作用。 Found this guy's tutorial on Youtube它给了我下面的错误:在MVC3中填充下拉列表不起作用

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

现在我出的选项。

这是我得到的值list(我认为):

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;} 
} 

这是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"); 
    } 

这是View

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

    </div> 

不知何故,它不适合我。我感谢任何帮助和建议。

回答

1

将您的操作方法修改为使用ViewData而不是ViewBag,并且View标记将起作用。

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

您需要在GET操作中填充ViewData,而不是POST操作。通过命名下拉列表Categ以及MVC约定将自动查找ViewData容器。

+0

它的工作,非常感谢你。我已经失去了这几个小时。 –

+0

@Szalasi Szabolcs不​​客气 – heads5150

+0

@ heads5150:我猜只是ViewData和ViewBag不同,ViewBag是'dynamic'类型,而ViewData是'dictionary'类型。那么它是如何工作的?有这些类型的东西吗? – RGR