我試圖填充一個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'始終爲空。 我在做什麼錯?
它的工作原理!非常感謝:) – 2013-04-08 14:58:26
我對此有另一個問題。實際上,DropDownList選擇的值返回'Book'的'ToString()'方法的值。 所以我必須把Ids放在我的DropDownList中,但我希望列表顯示標題和選定的值作爲Id。 有沒有辦法做到這一點? 現在,我使用這種方式:'ToString()'方法返回「Id - Title」,我使用SubString()來保存唯一的Id。 但我想DropDownList只顯示標題沒有Id。 – 2013-04-09 08:16:19
您傳遞給DropDown的'SelectList'類是一個'IEnumerable',其中'SelectListItem'有2個屬性:'Value'和'Text'。您可以將您的Book實例的'Id'和'Text'設置爲您想要的任何格式。 –
2013-04-09 08:24:19