当搜索的属性为null时,MVC搜索栏抛出NullException

时间:2015-07-21 14:45:29

标签: asp.net-mvc search lambda nullreferenceexception

我正在使用asp.net教程实现搜索栏

http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

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传递得很好。

由于

1 个答案:

答案 0 :(得分:0)

    if(!String.IsNullOrEmpty(searchString))
    {
        vm = vm.Where(s => !string.IsNullOrEmpty(s.Description) &&
            s.Description.Contains(searchString));   
    }