【发布时间】:2015-11-15 00:06:24
【问题描述】:
我目前有一个搜索表单,它有三个字段(一个下拉列表和两个日期范围的 Nullable 日期字段),根据我在 asp 中看到的,所有这些都是执行查询所必需的.net/mvc 文档,要执行验证,我需要创建一个 HttpGet 操作方法来构建模型显示页面,然后使用 HttpPost 获取该模型并验证它(以及之后它需要做的任何其他事情, RedirectToAction 等等)。
因为这是一个搜索查询,我宁愿避免使用 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]public ActionResult Search(SearchFormViewModel search) { ... }方法,这两种方法都返回带有@using (Html.BeginForm("Search", yourController, FormMethod.Get))的保存视图
标签: c# asp.net-mvc validation