繁体   English   中英

获取DropDownList的选定值。 Asp.NET MVC

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM