I am using Razorview and Entity Framework and I am trying to achieve the following: I have a dropdown(id=ColumnName) that has a list of column names and a textbox(id=SearchValue) for value to be searched from a table. On click of a button, I am retrieving the relevant data from the database( the record where the column name is 'ColumnName' selected and value='SearchValue'). This works fine but when I get the relevant data back, I lose the 'SearchValue' and 'ColumnName' selected. I am not sure how to save the value selected and entered and just get back the relevant data in the table. My code is as follows:
HTML:
<select id='mySelector' name="ColumnName">
<option value="">Please Select</option>
<option value='Country'>Country</option>
<option value='Title'>Title</option>
<option value='State'>State</option>
</select>
<input type="text" id="cs" name="SearchValue">
<input type="button" value="Search" onclick="location.href='@Url.Action("FilterByColumn", "CountryController")?SearchValue=' + document.getElementById('cs').value + '&ColumnName=' +document.getElementById('mySelector').value" />
<table id='myTable'>
// values
</table>
CountryController:
public ActionResult FilterByColumn(String ColumnName, String SearchValue)
{
if (!String.IsNullOrEmpty(SearchValue))
{
List<Country> result = new List<Country>();
result = db.Countries.ToList();
result = db.Countries.Where(ColumnName + ".Contains" + "(\"" + SearchValue.ToLower() + "\")").ToList();
return View(result);
}
return RedirectToAction("Index");
}
Note: I have other methods like create,edit in this controller.
I went ahead and did the searchvalue razor example, you would just have to do the proper razor elements for the columname which would be a selected item, again plenty of tutorials online.
<form id="myform" action="FilterByColumn" method="post">
<select id='mySelector' name="ColumnName">
<option value="">Please Select</option>
<option value='Country'>Country</option>
<option value='Title'>Title</option>
<option value='State'>State</option>
</select>
@if (ViewBag.searchval != "" ){
@Html.Raw ('<input type='text' id='cs' name='SearchValue' value="[email protected]+">");
}
else
{
@Html.Raw ('<input type="text" id="cs" name='SearchValue'>");
}
<input type="submit" value="Search" />
</form>
<table id='myTable'>
// values
</table>
CountryController:
public ActionResult FilterByColumn(String ColumnName)
{
ViewBag.searchval = "";
string SearchValue = Request.Form["SearchValue"];
if (SearchValue != "" )
{
List<Country> result = new List<Country>();
result = db.Countries.ToList();
result = db.Countries.Where(ColumnName + ".Contains" + "(\"" + SearchValue.ToLower() + "\")").ToList();
ViewBag.searchval = SearchValue;
return View(result);
}
return RedirectToAction("Index");
}