我想添加一個文本框(日期)和按鈕到我的報告,它過濾數據。下面MVC日期驗證搜索輸入/文本框的剃刀視圖MVC
的工作,但輸入仍必須驗證(必須是DATE)在客戶端(和服務器端如果可能的話)
我的模型看起來是這樣的:
public class DailyReport
{
public int DailyReportID { get; set; }
public DateTime? ReportDate { get; set; }
}
查看:
@model IEnumerable<project_name.Models.DailyReport>
@* text box and button: *@
@using (Html.BeginForm("Index", "DailyReport", FormMethod.Get))
{ <p>
Title: @Html.TextBox("SearchDateString")
<input type="submit" value="Filter" />
</p>
}
@* display dates*@
@foreach (var item in Model)
{ @Html.DisplayFor(modelItem => item.ReportDate)
}
我的控制器:
public ViewResult Index(String SearchDateString)
{
var dailyreport = db.DailyReport.Include(d => d.Site);
if (!String.IsNullOrEmpty(SearchDateString))
{
DateTime search_date = Convert.ToDateTime(SearchDateString);
dailyreport = dailyreport.Where(r => r.ReportDate == search_date);
}
return View(dailyreport.ToList());
}
有人可以幫我嗎? 如何確保在文本框中輸入有效的日期? 我應該爲此輸入創建另一個帶有日期字段的模型嗎?
鯊魚您好。我的輸入框目前不直接引用ReportDate。它使用文本框將字符串SearchDateString傳遞給控制器,該控制器將其轉換爲日期。我如何驗證SearchDateString輸入? – 2012-02-10 14:00:09
@DavidSmit看我的編輯。使用'TextBoxFor'幫助器將其向右推到模型上。您的驗證將發生在那裏。 – 2012-02-10 14:05:39
嗨鯊 在視圖中,該模型被聲明爲IEnumerable,因爲它是一個列表。當我添加你的建議時,我得到錯誤: ** System.Collections.Generic.IEnumerable'沒有包含'ReportDate'的定義,也沒有擴展方法'ReportDate'接受第一個參數鍵入** –
2012-02-10 14:22:48