ASP.NET MVC根据下拉列表中选择的选项筛选数据



我是MVC世界的新手,如果问题很简单,请原谅。

我正在尝试构建一个项目,让用户能够使用下拉列表选择要搜索的字段(LastName、FirstName、Department和Location(。用户可以在文本框中键入搜索词,然后单击"搜索"按钮。(根据下拉列表中选择的选项筛选数据,然后输入与下拉列表中所选选项匹配的内容(

问题是:我只能在字段中搜索,文本框无法读取下拉列表中的值。

我的型号是:

public class Employee
{
public int EmployeeId { get; set; }
[Required]
[StringLength(50, MinimumLength = 1)]
public string LastName { get; set; }
[Required]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
public string Department { get; set; }
[StringLength(50)]
public string Location { get; set; }
}

我的控制器是:

public ActionResult Index(string sortOrder, string searchString)
{
ViewBag.EmployeeList = new List<SelectListItem>
{
new SelectListItem{Selected=true, Text="LastName", Value="LastName" },
new SelectListItem{Selected=true, Text="FirstName", Value="FirstName" },
new SelectListItem{Selected=true, Text="Department", Value="Department" },
new SelectListItem{Selected=true, Text="Location", Value="Location" },
};
var employee = from e in db.Employee
select e;
if (!String.IsNullOrEmpty(searchString))
{
employee = employee.Where(s => s.FirstName.Contains(searchString));
}
return View(employee);
}

我的观点是:

<p>
All: @Html.DropDownList( "EmployeeList");
Search By: @Html.TextBox("searchString")<br />
<input type="submit" value="Search">
</p>

我不知道如何使用下拉列表来选择相应的字段,并让搜索框进行搜索。例如,如果我选择";位置";,我可以输入一些关于";"位置";在文本框中进行搜索,但仅限于Location,而不是FirstName或其他

这是从View 传递selectOption和searchtext的控制器

public ActionResult Index(string SelectOption, string SearchText)
{
var model = from s in db.Employee
select s;
if (!String.IsNullOrEmpty(SearchText) )
{
switch (SelectOption)
{
case "Email":
model = model.Where(a => 
a.Email.ToLower().Contains(SearchText.ToLower()));
break;
case "Forname":
model = model.Where(a => 
a.Forename.ToLower().Contains(SearchText.ToLower()));
break;
case "Surname":
model = model.Where(a => 
a.Surname.ToLower().Contains(SearchText.ToLower()));
break;
}
}


return View(model.ToList());
}

至于视图,您确实需要一直使用viewbag进行下拉列表。有时纯纯html可以做得更好。

@model IEnumerable<Incendo.Entities.Employee>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
<label for="selectoption">Select Option:</label>
<select id="SelectOption" name="SelectOption">
<option value="Email">Email</option>
<option value="Surname">Surname</option>
<option value="Forename">Forename</option>
</select>
<br />
@Html.Label("Search Text")
@Html.TextBox("SearchText") 
<input type="submit" value="Search" />
}

<table class="table table-responsive">
@foreach (var item in Model)
{
<tr>
<td>@item.Forename </td>
<td>@item.Surname </td>
<td>@item.Email  </td>
</tr>
}

最后,请记住将模型引用更改为您自己的命名空间

最新更新