2011-12-17 44 views
1

這裏是我的項目類:如何從ASP.NET MVC 3控制器中的列表框中獲取值?

public class Item 
{ 
    public int ItemId { get; set; } 
    public string Name { get; set; } 
    public virtual List<Tag> Tags { get; set; } 
} 

這裏是我的GET操作:

// 
// GET: /Home/AddItem/ 

public ActionResult AddItem() 
{ 
    List<Tag> Tags = Db.Tags.ToList(); 

    ViewBag.Tags = new SelectList(Tags, "TagId", "Name"); 

    return View(); 
} 

這是我的觀點:

@model MySite.Models.Item 

@using (Html.BeginForm()) { 
    //... 

    @Html.ListBox("Tags") 

    //... 
} 

最後,這裏是我的POST操作:

問題是Item.Tags.ToList()在POST動作中總是空的...就像ListBox的選定值根本沒有被髮送。

卡住了。請幫忙。

回答

3

我假設TagId是整數。

public class Item 
{ 
    public int ItemId { get; set; } 
    public string Name { get; set; } 
    public virtual List<int> Tags { get; set; } 
} 

[HttpPost] 
public ActionResult AddItem(Item Item) 
{ 
    List<int> NewItemTags = Item.Tags.ToList(); 
} 

同樣在查看您的ListBox應該有Name =「Tags」。如果您使用ListBoxFor,則無需擔心。

如果還有問題,請提供更多與查看相關的信息。

+0

它的工作!謝謝,@dotnetstep! – 2011-12-17 15:24:43

相關問題