私はビュー内にドロップダウンリストを持っています。私が望むのは、ユーザーがDropdownlist内の値を選択するたびに、コントローラは選択された値をとり、データベースへのクエリのパラメータとして使用します。ここでAsp.Net MVCドロップダウンリストの値としてパラメータ
が図である。
@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
を使用してみましたが、あるObject Reference Not Set To An Instance Of object
言います。だから私はRequest.Form
を使うことに決めました。しかし、まだstring val
に値が入っているかわからない
どのように選択した値をコントローラに送信しますか?それはフォーム提出を通じてですか?またはajax? – Shyju
@Shyju:私はこの質問を参照して、値をコントローラに送ります。 https://stackoverflow.com/questions/27901175/how-to-get-dropdownlist-selectedvalue-in-controller-in-mvc – Icon
フォーム提出を行う場合、あなたのコード 'string val = Request.Form [" Dropdown "];'うまくいくはずです。なぜそれは動作していないと思いますか?あなたのコードをデバッグしましたか?ブレークポイントを置き、コードをデバッグしてください。 – Shyju