我是整个 MVC 世界的新手,如果问题很简单,请见谅。
我正在尝试构建一个项目,让用户应该能够使用下拉列表选择要搜索的字段(姓氏、名字、部门和位置)。用户可以在文本框中键入搜索词并单击“搜索”按钮。 (根据下拉列表中选择的选项过滤数据,然后输入与下拉列表中选择的选项匹配的内容)
问题是:我只能在一个字段中搜索,而我的下拉列表中的值无法被文本框读取。
我的模型是这样的:
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”,我可以在文本框中输入一些关于“Location”的关键字进行搜索,但仅限于Location,而不是FirstName 或其他
答案 0 :(得分:0)
这是从视图传递 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>
}
最后记得把模型引用改成自己的命名空间