Asp.Net MVC 下拉列表值作为参数

Asp.Net MVC Dropdownlist Value As Parameter

我在视图中有一个下拉列表。我想要的是,每次用户 select Dropdownlist 中的值时,控制器采用 selected 值并将其用作查询数据库的参数。

这是视图:

 @using (Html.BeginForm("Index", "Home"))
{

     @Html.DropDownList("Dropdown", new List<SelectListItem>
                       {new SelectListItem {Text="All Assignments", Value = "All" },new SelectListItem {Text="Open Assignments", Value = "Admin"},
                       new SelectListItem{Text="Close Assignments", Value = "Admin"}},"Select One", new { @class = "form-control", style = "width:300px; height:35px;" })

    <h3 style="margin-top:10px;">List of Assignment</h3>
      <table id="myTable" class="table table-hover table-striped">
          //Table Content
      </table>


}

这是控制器:

public ActionResult Index(string username)
        {
            string val = Request.Form["Dropdown"];
            val = Request["Dropdown"];
            string nama = string.Empty;
            if (val == null)
            {
                nama = "admin";
            }
            else
            {
                nama = val;
            }

            if (Session["username"] != null)
            {

                string user = Session["username"].ToString();
                SqlConnection conn = new SqlConnection(connString);
                conn.Open();
                string sqlQuery = @"select Animals, Gender from dbo.Animals where Pemilik = @user";

                //string h = x => x.
                SqlCommand cmd = new SqlCommand(sqlQuery, conn);
                cmd.Parameters.AddWithValue("@user", nama);
                DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                conn.Close();
                return View(dt);
            }
            else
            {
                return RedirectToAction("Login", "Login");
            }

        }

我尝试使用 FormCollection 获取下拉列表的 selected 值,但显示 Object Reference Not Set To An Instance Of object。所以我决定使用 Request.Form。但是,我仍然不确定 string val 是否包含值。

如果您将表单提交给操作方法,您的代码 string val = Request.Form["Dropdown"]; 将起作用。但是由于您希望每次用户更改选项时都发送值,因此您需要通过 javascript 提交表单。您可以在 SELECT 元素上监听更改事件并提交表单。

下面的 javascript 代码就可以了。

$(function () {

    $("#Dropdown").change(function(e) {
        $(this).closest("form").submit();
    });

});

现在在您的操作方法中放置一个断点,并在执行行 string val = Request.Form["Dropdown"];.

后检查 val 变量的值

或者,您可以将名称与 SELECT 元素的名称相匹配的参数添加到操作方法中。

public ActionResult Index(string username,string Dropdown)
{
  string val = Dropdown;
  // to do : Return something
}