從先前的帖子下面就結果的列表:Adding a search form using a DateTime template顯示在搜索表單,它使用一個ViewModel
...但是那並不是」不要使用我之前發佈的回覆中建議的ViewModel。
我想,以幫助從搜索,這將需要兩個日期(自/至)的基礎上,一個視圖模型:
public class SearchViewModel
{
[Required]
public DateTime From { get; set; }
[Required]
public DateTime To { get; set; }
}
我瀏覽/搜索/ 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/
public ActionResult Index()
{
SearchViewModel svm = new SearchViewModel();
svm.From = DateTime.Today;
svm.To = DateTime.Today;
return View(svm);
}
到目前爲止好 - 我的視圖顯示與d文本框ates默認爲今天(使用DateTime助手)。當我點擊搜索,代碼轉到SearchController //郵編:/搜索如下:
//
// 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());
}
我在哪裏,現在不能確定是近一郵政控制器的線 - 我該如何返回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'.
我豈是混合蘋果和梨 - 反正是有顯示在從和在搜索框的房間列表(視圖模型) ?
謝謝
馬克
要麼你有一個TURIN電腦發佈給你,或者你是驚人地多產於幫助這裏的人 - 或者,我很感激 - 它幫助我,更具體地說,我試圖幫助這個社區的人中心,非常多!我也傳遞他們的感謝。乾杯! – Mark
有沒有什麼辦法可以將搜索表單保留在results.cshtml的頂部 - 或者是進入PartialViews的區域嗎? – Mark
是的,您可以,這就是我的答案的第二部分涵蓋的內容=>將屬性添加到現有視圖模型中,該模型將包含房間集合並在視圖內測試此屬性是否已定義。 –