如何在异步控制器中验证modelstate

时间:2011-04-13 01:01:40

标签: asp.net asp.net-mvc asynchronous controller modelstate

我正在尝试使用异步控制器,但我无法弄清楚如何验证用户输入。

以下是我的控制器中定义的两个异步方法。我应该在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);
}

2 个答案:

答案 0 :(得分:3)

以下似乎对我有用。我最终在两种方法中都检查了modelstate。将初始模型添加为已完成方法的参数。 Asp.net Mvc似乎坚持两种方法之间的模型状态

    [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);
    }

答案 1 :(得分:0)

您可以使用

AsyncManager.Parameters['ModelIsValid'] = false;

在Async方法中,

if(AsyncManager.Parameters['ModelIsValid'] == false) { ... }
在Completed方法中

检查并查看是否存在验证问题。只是不要增加未完成的操作,也不要执行任何进一步的逻辑。将触发Completed方法,您可以检查该值。