上一篇文章的后续:使用 DateTime 模板添加搜索表单
...但这并没有像我上一篇文章的答案中所建议的那样使用 ViewModel。
我正在尝试帮助搜索,这将需要两个日期(从/到),基于以下 ViewModel:
public class SearchViewModel
{
[Required]
public DateTime From { get; set; }
[Required]
public DateTime To { get; set; }
}
我的 Views/Search/Index.cshtml 是:
@model ttp.Models.SearchViewModel
@{
ViewBag.Title = "Search Availability";
}
<h2>Search Availability</h2>
@using (Html.BeginForm())
{
<div class="row">
<div class="span2">@Html.LabelFor(x => x.From)</div>
<div class="span2">@Html.EditorFor(x => x.From)</div>
<div class="span2">@Html.ValidationMessageFor(x => x.From)</div>
</div>
<div class="row">
<div class="span2">@Html.LabelFor(x => x.To)</div>
<div class="span2">@Html.EditorFor(x => x.To)</div>
<div class="span2">@Html.ValidationMessageFor(x => x.To)</div>
</div>
<div class="row">
<div class="span2 offset2"><button type="submit">Search</button></div>
</div>
}
Get: /Search/Index 控制器是:
//
// GET: /Search/
public ActionResult Index()
{
SearchViewModel svm = new SearchViewModel();
svm.From = DateTime.Today;
svm.To = DateTime.Today;
return View(svm);
}
到目前为止一切顺利 - 我的视图显示日期默认为今天的文本框(使用 DateTime Helper)。当我单击 Search 时,代码转到 SearchController // Post: / Search,如下所示:
//
// Post: /Search/
[HttpPost]
public ActionResult Index(SearchViewModel searchViewModel)
{
if (!ModelState.IsValid)
{
// Not valid, so just return the search boxes again
return View(searchViewModel);
}
// Get the From/To of the searchViewModel
DateTime dteFrom = searchViewModel.From;
DateTime dteto = searchViewModel.To;
// Query the database using the posted from/to dates
IQueryable<Room> rooms = db.Rooms.Where(r => r.Clients.Any(c => c.Departure >= dteFrom && c.Departure < dteTo));
// This is where I'm unsure
ViewBag.Rooms = rooms.ToList();
return View(rooms.ToList());
}
我现在不确定的是 Post 控制器的最后几行 - 我如何返回 IQueryable 房间中的房间列表 - 并在屏幕上显示房间列表?我是否重定向到另一个视图(如果是,我如何将房间列表传递给该视图)?如果我只是尝试运行上面的代码,我会收到错误消息:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[ttp.Models.Room]', but this dictionary requires a model item of type 'ttp.Models.SearchViewModel'.
我是否试图混合苹果和梨 - 是否有在 From 和 To 搜索框(ViewModel)下显示房间列表?
谢谢,
标记