加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 获取DropDownList的选定值. Asp.NET MVC

发布时间:2020-12-15 04:24:14 所属栏目:百科 来源:网络整理
导读:我正在尝试填充一个DropDownList并在提交表单时获取选定的值: 这是我的模特儿: public class Book{ public Book() { this.Clients = new ListClient(); } public int Id { get; set; } public string JId { get; set; } public string Name { get; set; }
我正在尝试填充一个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’始终为空.
我究竟做错了什么?

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读