2012-01-26 121 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

相關問題