[英]Get the selected value of a DropDownList. Asp.NET MVC
我正在嘗試填充DropDownList並在提交表單時獲取所選值:
這是我的模型:
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>
}
單擊時,Action中的參數'book'始終為null。 我究竟做錯了什么?
在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();
}
您可以使用DropDownListFor,如下所示,它更簡單
@Html.DropDownListFor(m => m.Id, new SelectList(Model.Books,"Id","Name","1"))
(你需要一個強類型視圖 - View包不適合大型列表)
public ActionResult Action(Book model)
{
if (ValidateFields()
{
var Id = model.Id;
...
我認為這更容易使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.