尝试使用视图模型为您搜索屏幕的情况下,你需要在你随后的搜索中添加更多的过滤项目。那么你将不会有每个搜索过滤器的参数,只有一个,即你的视图模型。你现在拥有它的方式现在也可以工作,下面只是一种替代方法。
视图模型可能是这样的:
public class SearchViewModel
{
public string SearchString { get; set; }
// Other filter items if you need anything else
}
你的控制器的操作方法
public ActionResult Search()
{
SearchViewModel viewModel = new SearchViewModel();
return View(viewModel);
}
从控制器中删除你的数据访问,并通过服务层或存储库工作:
[HttpPost]
public ActionResult Search(SearchViewModel viewModel)
{
// Check for null viewModel
if (!ModelState.IsValid)
{
// A possible failed validation is when no search string was entered,
// and then you don't want to do any database calls.
// Just pass back the view model and let the view handle the displaying of errors
return View(viewModel);
}
// If validation succeeds now you can use your search string to retrieve data
searchService.Search(viewModel.SearchString);
// Do what else you need to do and the return the correct view
return View();
}
而您的搜索视图可能如下所示:
@model YourProject.ViewModels.Searches.SearchViewModel
@using (Html.BeginForm())
{
@Html.TextBoxFor(x => x.SearchString)
@Html.ValidationMessageFor(x => x.SearchString)
<button id="searchButton" type="submit">Search</button>
}
我希望现在更有意义。
感谢您宝贵的回复,这对我非常有帮助。我需要另一个帮助,我有一列需要根据某些标准自动生成id值,但不能识别,您能帮我采用哪种方法带示例代码 – shan
Hi @ sanjay1234,您的搜索请求对我来说有点太模糊,因此无法给您一个有意义的答案。我建议你尽可能详细地创建一个新的问题,我会留意的。如果您认为它已回答您的问题,请接受此答案 – NinjaNye