tahirraza tahirraza - 2 months ago 23
ASP.NET (C#) Question

How to use DropdownList selected Value to filter data

I have a dropdown,a TextBox and a Button,DropDdown contains ColumnNames (Name,Cpr),to see filtered data user selects a value from dropDown,enters a string and clicks Button. For doing this i wrote following code,but unable to get DropDown Selected Value,except this problem code working perfectly.plz tell me where im doing mistake.
Following is my Controller


public ActionResult Index(string searchType,FormCollection frm)
{
List<SelectListItem> obj = new List<SelectListItem>();
obj.Add(new SelectListItem { Text = "Agent Name", Value = "Name", Selected = true });
obj.Add(new SelectListItem {Text = "CPR Number", Value = "Cpr"});
ViewBag.cmb = obj;


var agents = from s in db.Agents
select s;

if (searchType != null)
{
ViewBag.searchString = searchType;
string cmbColumnSelection = frm["cmb"];

switch (cmbColumnSelection)
{
case "Name": // Table=Agent,Column=Name

agents = agents.Where(s => s.Name.ToString().Contains(searchType));
break;
default:
agents = agents.Where(s => s.Cpr.ToString().Contains(searchType));
break;
}
}

return View(agents.ToList());
} `


In View:

@using (Html.BeginForm("Index", "Agent", FormMethod.Get))
{
<p>
@Html.TextBox("searchType", ViewBag.searchString as string)
Select Filter : @Html.DropDownList("cmb")
<input type="submit" value="Submit" class="btn btn-primary" />
</p>
}

Answer

Don't mix action input parameters and form collection. You have a good start with searchType, stick to the same with cmb and drop form collection altogether:

public ActionResult Index(string searchType, String cmb)

That's it, cmb will contain the value posted from drop down. Just use it now:

string cmbColumnSelection = cmb;

or even

switch (cmb)
{...