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.Outsta开发者_JAVA技巧ndingOperations.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);
}
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
[HttpPost]
[ValidateAntiForgeryToken]
public void SearchAsync(BusinessSearchForm searchForm)
{
if (ModelState.IsValid)
{
AsyncManager.OutstandingOperations.Increment();
new Thread(() =>
{
if (ModelState.IsValid)
{
var suggestions = _searchBusinessSvc.GetSuggestions(searchForm.BusinessName, searchForm.StreetAddress, searchForm.City, searchForm.PostalCode);
AsyncManager.Parameters["suggestions"] = suggestions;
}
AsyncManager.Parameters["searchForm"] = searchForm;
AsyncManager.OutstandingOperations.Decrement();
}).Start();
}
}
public ActionResult SearchCompleted(BusinessSearchForm searchForm,IEnumerable<BusinessSuggestionBase> suggestions)
{
if (ModelState.IsValid)
{
TempData["suggestions"] = suggestions;
return RedirectToAction("SearchResult");
}
return View(searchForm);
}
You can use
AsyncManager.Parameters['ModelIsValid'] = false;
in the Async method, and
if(AsyncManager.Parameters['ModelIsValid'] == false) { ... }
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.
精彩评论