当正在搜索的 属性 为空时,MVC 搜索栏抛出 NullException
MVC Search Bar throwing NullException when property being searched is null
我正在使用 asp.net 教程实现搜索栏
public ActionResult Index(string sortOrder, string searchString = null)
{
var viewModels = new List<ScheduleViewModel>();
foreach (var schedule in db.Schedule)
viewModels.Add(GetViewModelFromSchedule(schedule));
//--vm for viewModel
var vm = from s in viewModels
select s;
if(!String.IsNullOrEmpty(searchString))
{
vm = vm.Where(s =>
s.Description.Contains(searchString));
}
//--CODE FOR SORT ORDER THAT I LEFT OUT BECAUSE THE EXCEPTION IS THROWN ABOVE
return View(vm.ToList());
}
我的 HTML 在视图中看起来像这样
<form method="get" action="@Url.Action("Index")" >
<input type="search" name="searchString" />
<input type="submit" value="Filter" />
</form>
当我进行调试并将鼠标悬停在 s.Description 上时,它显示为 null。
searchString 顺利通过。
谢谢
if(!String.IsNullOrEmpty(searchString))
{
vm = vm.Where(s => !string.IsNullOrEmpty(s.Description) &&
s.Description.Contains(searchString));
}
我正在使用 asp.net 教程实现搜索栏
public ActionResult Index(string sortOrder, string searchString = null)
{
var viewModels = new List<ScheduleViewModel>();
foreach (var schedule in db.Schedule)
viewModels.Add(GetViewModelFromSchedule(schedule));
//--vm for viewModel
var vm = from s in viewModels
select s;
if(!String.IsNullOrEmpty(searchString))
{
vm = vm.Where(s =>
s.Description.Contains(searchString));
}
//--CODE FOR SORT ORDER THAT I LEFT OUT BECAUSE THE EXCEPTION IS THROWN ABOVE
return View(vm.ToList());
}
我的 HTML 在视图中看起来像这样
<form method="get" action="@Url.Action("Index")" >
<input type="search" name="searchString" />
<input type="submit" value="Filter" />
</form>
当我进行调试并将鼠标悬停在 s.Description 上时,它显示为 null。 searchString 顺利通过。
谢谢
if(!String.IsNullOrEmpty(searchString))
{
vm = vm.Where(s => !string.IsNullOrEmpty(s.Description) &&
s.Description.Contains(searchString));
}