【问题标题】:Get the selected value of a DropDownList. Asp.NET MVC获取 DropDownList 的选定值。 ASP.NET MVC
【发布时间】:2013-03-30 16:20:40
【问题描述】:

我正在尝试填充 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”始终为空。 我做错了什么?

【问题讨论】:

    标签: c# .net asp.net-mvc razor asp.net-mvc-4


    【解决方案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();
    }
    

    【讨论】:

    • 我对此还有另一个问题。实际上,DropDownList 选择的值返回的是 Book 的 ToString() 方法的值。所以我必须将 Ids 放在我的 DropDownList 中,但我希望列表显示标题,并且选择的值是 Id。有没有办法做到这一点?现在,我使用这种方式:ToString() 方法返回“Id - Title”,我使用SubString() 只保留 Id。但我希望 DropDownList 只显示没有 ID 的标题。
    • 您传递给 DropDown 的 SelectList 类是 IEnumerable&lt;SelectListItem&gt;,其中 SelectListItem 有 2 个属性:Value 和 Text。您可以将 Value 设置为 Book 实例的 Id 并将 Text 设置为您想要的任何格式。
    • @Darin Dimitrov,太棒了!这就是我想做的!你是向导:)。
    【解决方案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;
            ...        
    

    我认为这更易于使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多