获得一个DropDownList的选定值。 Asp.NET MVC [英] Get the selected value of a DropDownList. Asp.NET MVC

查看:245
本文介绍了获得一个DropDownList的选定值。 Asp.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图填充一个DropDownList,并获得选择的值,当我提交表单:

I'm trying to populate a DropDownList and to get the selected value when I submit the form:

下面是我的模型:

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; }
}

我的控制器:

My Controllers :

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

当我点击,参数书的行动总是空。 我究竟做错了什么?

When I click, the parameter 'book' in the Action is always null. What am I doing wrong?

推荐答案

在HTML中的下拉框将只简单标量值。你的情况这将是所选书籍的ID:

In HTML a dropdown box sends only simple scalar values. In your case that would be the id of the selected book:

@Html.DropDownList("selectedBookId", (SelectList)ViewBag.Books)

,然后调整你的控制器动作,这样你将检索本书从获取传递到您的控制器操作中的ID:

and then adapt your controller action so that you will retrieve the book from the id that gets passed to your controller action:

[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的选定值。 Asp.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆