获取 DropDownList 的选定值.ASP.NET MVC [英] Get the selected value of a DropDownList. Asp.NET MVC
本文介绍了获取 DropDownList 的选定值.ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试填充 DropDownList 并在提交表单时获取所选值:
I'm trying to populate a DropDownList and to get the selected value when I submit the form:
这是我的模型:
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"始终为空.我做错了什么?
When I click, the parameter 'book' in the Action is always null. What am I doing wrong?
推荐答案
在 HTML 中,下拉框仅发送简单的标量值.在您的情况下,这将是所选书籍的 ID:
In HTML a dropdown box sends only simple scalar values. In your case that would be the id of the selected book:
@Html.DropDownList("selectedBookId", (SelectList)ViewBag.Books)
然后调整您的控制器操作,以便您从传递给您的控制器操作的 id 中检索图书:
and then adapt your controller action so that you will retrieve the book from the id that gets passed to your controller action:
[Authorize]
[HttpPost]
public ActionResult Action(string selectedBookId)
{
if (ValidateFields()
{
Book book = FetchYourBookFromTheId(selectedBookId);
var data = GetDatasAboutBookSelected(book);
ViewBag.Data = data;
return View();
}
return View();
}
这篇关于获取 DropDownList 的选定值.ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文