0
我目前有一個搜索表單,它有三個字段(一個下拉列表和兩個日期範圍的Nullable
日期字段),並且所有這些都是執行查詢所需的,已經在asp.net/mvc文檔中看到,爲了執行驗證,我需要創建一個HttpGet
動作方法來構建模型顯示頁面,然後使用HttpPost
來獲取該模型並驗證它(以及其他任何需要的內容之後,RedirectToAction
等等)。Http GET驗證ASP.NET MVC 5
因爲這是一個搜索查詢,我寧願避免使用HTTP POST
動詞和以http堅持GET
動詞,而不是,但我不能爲我的生活弄清楚如何,而不包含錯誤信息來實現這一出現在最初的請求(記住Nullable
日期字段),或者,如果我把默認值,ModelState
是有效的。
這裏是我的兩個方法:
[HttpGet]
public ActionResult Index()
{
HomeIndexViewModel model = new HomeIndexViewModel()
{
SearchForm = new SearchFormViewModel()
{
GeoCounterDefinitions = geocounterservice.getAllDefinitions()
.Select(x => new SelectListItem()
{
Text = x.CounterKey + " " + x.FriendlyDesc,
Value = x.CounterKey.ToString()
})
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(SearchFormViewModel search)
{
if (!ModelState.IsValid)
{
return View(new HomeIndexViewModel() {
SearchForm = new SearchFormViewModel()
{
CounterKey = search.CounterKey,
StartDate = search.StartDate,
EndDate = search.EndDate,
GeoCounterDefinitions = geocounterservice.getAllDefinitions()
.Select(x => new SelectListItem()
{
Text = x.CounterKey + " " + x.FriendlyDesc,
Value = x.CounterKey.ToString()
})
}
});
}
return RedirectToAction("Search");
}
你可以使用現有的' Index()'方法初始調用,然後有一個(說)'[HttpGet]公共ActionResult搜索(SearchFormViewModel搜索){...}'方法與兩個方法返回保存視圖與@using(Html.BeginForm( 「搜索」,yourContr oller,FormMethod.Get))' –