我不再有问题,因为我知道如何做到这一点
Index.cshtml
@model IEnumerable<ContactManager.Models.Contacts>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2></h2>
@using (Html.BeginForm()) {
<p>@Html.TextBox("SearchString")
<input type="submit" value="Search" /></p>
}
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.LastName)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th>
@Html.DisplayNameFor(model => model.State)
</th>
<th>
@Html.DisplayNameFor(model => model.Zip)
</th>
<th>
@Html.DisplayNameFor(model => model.Phone)
</th>
<th>
Modify
</th>
</tr>
@foreach (var item in Model) {
var lncolor = "white" ;
var zipcolor = "black";
switch (item.LastName) {
case "Whited":
lncolor = "yellow";
break;
default:
lncolor = "white";
break;
}
if (item.ID % 2 == 0) {
zipcolor = "red";
} else {
zipcolor = "black";
}
<tr>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td bgcolor="@lncolor">
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.State)
</td>
<td>
<font color="@txtcolor">
@Html.DisplayFor(modelItem => item.Zip)
</font>
</td>
<td>
@Html.DisplayFor(modelItem => item.Phone)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
我的控制器的相对部分
private ContactsDBContext db = new ContactsDBContext();
// GET: Contacts
public ActionResult Index(string searchString)
{
var contacts = from c in db.Contact
select c;
if (!String.IsNullOrEmpty(searchString)) {
contacts = contacts.Where(s => s.FirstName.Contains(searchString) || s.LastName.Contains(searchString) || s.Address.Contains(searchString)
|| s.City.Contains(searchString) || s.State.Contains(searchString) || s.Zip.Contains(searchString) || s.Phone.Contains(searchString));
}
//return View(db.Contact.ToList());
return View(contacts);
}
我设法找到了一种方法来完成我想要做的事情。我已经更新了代码以反映我所做的事情。我不确定这是实现这一目标的最优雅方式,所以如果有人有任何更好的建议我都会听到。