2013-04-08 89 views
9

我試圖填充一個DropDownList,當我提交表單,以獲得所選擇的值:獲取DropDownList的選定值。 Asp.NET MVC

這裏是我的模型:

public class Book 
{ 
    public Book() 
    { 
     this.Clients = new List<Client>(); 
    } 

    public int Id { get; set; } 
    public string JId { get; set; } 
    public string Name { get; set; } 
    public string CompanyId { get; set; } 
    public virtual Company Company { get; set; } 
    public virtual ICollection<Client> Clients { get; set; } 
} 

我的控制器:

[Authorize] 
    public ActionResult Action() 
    { 
     var books = GetBooks(); 
     ViewBag.Books = new SelectList(books); 
     return View(); 
    } 

    [Authorize] 
    [HttpPost] 
    public ActionResult Action(Book book) 
    { 
     if (ValidateFields() 
     { 
      var data = GetDatasAboutBookSelected(book); 
      ViewBag.Data = data; 
      return View(); 
     } 
     return View(); 
    } 

我的表格:

@using (Html.BeginForm("Journaux","Company")) 
{ 
<table> 
    <tr> 
     <td> 
      @Html.DropDownList("book", (SelectList)ViewBag.Books) 
     </td> 
    </tr> 
    <tr> 
     <td> 
      <input type="submit" value="Search"> 
     </td> 
    </tr> 
</table> 
} 

當我點擊時,PA Action中的rameter'book'始終爲空。 我在做什麼錯?

回答

17

在HTML中,下拉框只發送簡單的標量值。你的情況,這將是所選擇的書的id:

@Html.DropDownList("selectedBookId", (SelectList)ViewBag.Books) 

,然後適應您的控制器動作,這樣你將得到數據傳遞給你的控制器動作ID檢索圖書:

[Authorize] 
[HttpPost] 
public ActionResult Action(string selectedBookId) 
{ 
    if (ValidateFields() 
    { 
     Book book = FetchYourBookFromTheId(selectedBookId); 
     var data = GetDatasAboutBookSelected(book); 
     ViewBag.Data = data; 
     return View(); 
    } 
    return View(); 
} 
+0

它的工作原理!非常感謝:) – 2013-04-08 14:58:26

+0

我對此有另一個問題。實際上,DropDownList選擇的值返回'Book'的'ToString()'方法的值。 所以我必須把Ids放在我的DropDownList中,但我希望列表顯示標題和選定的值作爲Id。 有沒有辦法做到這一點? 現在,我使用這種方式:'ToString()'方法返回「Id - Title」,我使用SubString()來保存唯一的Id。 但我想DropDownList只顯示標題沒有Id。 – 2013-04-09 08:16:19

+0

您傳遞給DropDown的'SelectList'類是一個'IEnumerable ',其中'SelectListItem'有2個屬性:'Value'和'Text'。您可以將您的Book實例的'Id'和'Text'設置爲您想要的任何格式。 – 2013-04-09 08:24:19

1

您可以如下使用DropDownListFor,就這麼簡單

@Html.DropDownListFor(m => m.Id, new SelectList(Model.Books,"Id","Name","1")) 

(你需要這樣的強類型視圖 - 快速袋不適合大名單)

public ActionResult Action(Book model) 
    { 
     if (ValidateFields() 
     { 
      var Id = model.Id; 
     ...   

我覺得這個比較簡單。