2012-01-26 32 views
0

我看过类似的帖子,但没有为我的情况工作。 我有一个表格,加载正常,我看到类别下拉列表中的所有类别。 问题是当我尝试发布表单时。尝试使用下拉列表发布MVC表单时发生错误

我得到这个错误:

具有关键的“类别”的类型是“System.String”的,但必须是类型“的IEnumerable”的ViewData的项目。

@ Html.DropDownList( “类别”,Model.Categories)< - 红色

这是我的观点:

@using (Html.BeginForm("Save", "Album", FormMethod.Post, new { id = "frmNewAlbum" })) 
{     
    @Html.DropDownList("Category", Model.Categories) 
} 

这里是我的模型:

public class AlbumModel 
{   
     public string Title { get; set; } 

     public string Category { get; set; } 

     public List<SelectListItem> Categories { get; set; } <-- holds categories 
} 

这是控制器查看页面的操作:

[HttpGet] 
public ActionResult Save() 
     { 
      var model = new AlbumModel(); 
      var categories = new List<SelectListItem>() { new SelectListItem() { Text = "-- pick --" } }; 
      categories.AddRange(svc.GetAll().Select(x => new SelectListItem() { Text = x.Name, Value = x.Name })); 
      model.Categories = categories; 
      return View(model); 
     } 

行动接收帖子:

[HttpPost] 
    public ActionResult Save(AlbumModel model) 
    {    
       var album = new AlbumDoc() 
       {       
        Category = model.Category, 
        Title = model.Title, 
       }; 

       svc.SaveAlbum(album); 

     return View(model); 
    } 

回答

0

在您的文章的行动,你似乎重新显示了同样的观点,但你不填充您的视图模型的Categories属性,该属性将包含下拉列表值。顺便说一句,我会建议你使用强类型的帮手。所以:

public class AlbumController: Controller 
{ 
    [HttpGet] 
    public ActionResult Save() 
    { 
     var model = new AlbumModel(); 
     model.Categories = GetCategories(); 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Save(AlbumModel model) 
    {    
     var album = new AlbumDoc() 
     {       
      Category = model.Category, 
      Title = model.Title, 
     }; 
     svc.SaveAlbum(album); 
     model.Categories = GetCategories(); 
     return View(model); 
    } 

    private IList<SelectListItem> GetCategories() 
    { 
     return svc 
      .GetAll() 
      .ToList() 
      .Select(x => new SelectListItem 
      { 
       Text = x.Name, 
       Value = x.Name 
      }); 
    } 
} 

,并在您的视图:

@model AlbumModel 
... 
@using (Html.BeginForm("Save", "Album", FormMethod.Post, new { id = "frmNewAlbum" })) 
{     
    @Html.DropDownListFor(
     x => x.Category, 
     Model.Categories, 
     -- pick -- 
    ) 
} 
+0

第一个不能正常工作,它说:值不能为空。 参数名称:项目。第二个也给旧的错误。 – kheya 2012-01-26 23:15:01

+0

Darrin,这应该是一个阿贾克斯后并非完整的职位。为什么点击提交后刷新页面? – kheya 2012-01-26 23:20:24

+1

@Projapati - 因为你没有使用Ajax.BeginForm? – 2012-01-26 23:23:41

相关问题