I have a dropdownlist inside a view. What i want is, everytime user select the value inside Dropdownlist, the controller take the selected value and use it as parameter for query to database.
Here is the view :
@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>
}
And Here is the Controller:
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");
}
}
I tried using FormCollection
to get the dropdownlist selected value, but is says Object Reference Not Set To An Instance Of object
. So i decide to use Request.Form
. However, im still not sure that string val
contains value.