如何验证异步控制器中的模型状态
我正在尝试使用异步控制器,但无法弄清楚如何验证用户输入。
以下是我的控制器中定义的两个异步方法。我应该在 SearchAsync 方法或 SearchCompleted 方法中检查 ModelState.IsValid 吗?如果 SearchAsync 那么如何返回视图结果,因为它的返回类型为 void。如果 SearchCompleted 那么该方法将如何知道 searchForm 参数。
[HttpPost]
[ValidateAntiForgeryToken]
public void SearchAsync(BusinessSearchForm searchForm)
{
AsyncManager.OutstandingOperations.Increment();
new Thread(() =>
{
var suggestions = _searchSvc.GetSuggestions(searchForm.BusinessName, searchForm.StreetAddress, searchForm.City, searchForm.PostalCode);
AsyncManager.Parameters["suggestions"] = suggestions;
AsyncManager.OutstandingOperations.Decrement();
}).Start();
}
public ActionResult SearchCompleted(IEnumerable<BusinessSuggestionBase> suggestions)
{
return View(suggestions);
}
I am trying to use Async controller and am not able to figure out how would one validate the user input.
Following are the two async methods defined in my controller. Should I check for ModelState.IsValid in the SearchAsync method or SearchCompleted method. If SearchAsync then how will return the view result as its return type is void. If SearchCompleted then how will the method know about searchForm parameter.
[HttpPost]
[ValidateAntiForgeryToken]
public void SearchAsync(BusinessSearchForm searchForm)
{
AsyncManager.OutstandingOperations.Increment();
new Thread(() =>
{
var suggestions = _searchSvc.GetSuggestions(searchForm.BusinessName, searchForm.StreetAddress, searchForm.City, searchForm.PostalCode);
AsyncManager.Parameters["suggestions"] = suggestions;
AsyncManager.OutstandingOperations.Decrement();
}).Start();
}
public ActionResult SearchCompleted(IEnumerable<BusinessSuggestionBase> suggestions)
{
return View(suggestions);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下似乎对我有用。我最终在这两种方法中检查了模型状态。将初始模型作为参数添加到已完成的方法中。 Asp.net Mvc 似乎保留了两种方法之间的模型状态
The following seems to work for me. I end up checking for modelstate in both methods. Added the initial model as a param to the completed method. Asp.net Mvc seemed to persist the modelstate between the two methods
您可以
在 Async 方法和
Completed 方法中使用来检查是否存在验证问题。简单地不增加未完成的操作,并且不执行任何进一步的逻辑。 Completed 方法将触发,您可以检查该值。
You can use
in the Async method, and
in the Completed method to check and see if there was a validation issue. Simply do not increment the outstanding operations, and do not perform any further logic. The Completed method will fire, and you can check the the value.