c# - 获取 DropDownList 的选定值。 ASP.NET MVC

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

我正在尝试填充 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; }
}

我的 Controller :

    [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)

然后调整您的 Controller 操作,以便您可以从传递给您的 Controller 操作的 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();
}

关于c# - 获取 DropDownList 的选定值。 ASP.NET MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15881575/

相关文章:

c# - 使 WPF TextBox 拉伸(stretch)到可用空间而不随 Text 增长

.net - WinForms 中的水印文本框

asp.net-mvc - Paypal 使用哪个 KEY 以便我可以与我的网站同步?

c# - 重新使用继承的 FK 关系?

c# - 翻译 ninject ISecureDataFormat 绑定(bind)到 Autofac

.net - 调查从服务器通知 WPF 客户端的解决方案

c# - ASP.NET HttpContext 缓存在插入后立即删除

c# - 如何在 MVC SimpleMembership 中锁定/解锁用户

c# - 从 TFS 获取最新版本的文件

c# - 将 XML 消息反序列化为对象