Http GET验证ASP.NET MVC 5
问题描述:
我目前有一个搜索表单,它有三个字段(一个下拉列表和两个日期范围的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");
}
答
一种方式是一个非空的属性,以便添加到SearchFormViewModel
来检测,如果它是一个表单提交与否。
public class SearchFormViewModel
{
public bool IsSubmit {get; set;}
}
表单中的
与FormMethod.Get
Html.HiddenFor(m => m.IsSubmit, true) ;
然后你就可以在同样的动作把两个任务(搜索画面显示和实际搜索):
[HttpGet]
public ActionResult Index(SearchFormViewModel search)
{
if (search.IsSubmit) {
return ActualSearch(search) ;
}
// Display search page
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);
}
private ActionResult ActualSearch(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))' –