找一个DropDownList的选定值。 Asp.NET MVC(Get the selecte

2019-08-20 07:33发布

我试图填充一个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>
}

当我点击,在操作参数“书”总是空。 我究竟做错了什么?

Answer 1:

在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();
}


Answer 2:

您可以如下使用DropDownListFor,就这么简单

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

(您需要为这个强类型视图 - 快速袋不适合大名单)

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

我觉得这是更容易使用。



文章来源: Get the selected value of a DropDownList. Asp.NET MVC