我在MVC 4應用程序的控制器操作:何時應該將操作標記爲異步?
public ActionResult Index()
{
GetStartedModel gsModel = new GetStartedModel();
return View(gsModel);
}
和視圖模型:
public class GetStartedModel
{
public IEnumerable<SelectListItem> listA { get; set; }
public IEnumerable<SelectListItem> listB { get; set; }
public GetStartedModel()
{
TestDataWebServiceHelper service = new TestDataWebServiceHelper();
this.GetData(service);
}
private async void SetData(TestDataWebServiceHelper service)
{
listA = await this.SetListA(service);
listB = await this.SetListB(service);
}
private async Task<IEnumerable<SelectListItem>> SetListA(TestDataWebServiceHelper service)
{
List<String> rawList = new List<String>();
rawList = await service.GetValuesAsync("json");
return rawList.Select(x => new SelectListItem { Text = x, Value = x });
}
private async Task<IEnumerable<SelectListItem>> SetListB(TestDataWebServiceHelper service)
{
List<String> rawList = new List<String>();
rawList = await service.GetValuesAsync("json");
return rawList.Select(x => new SelectListItem { Text = x, Value = x });
}
}
當我把這個控制器動作我收到以下錯誤:
An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>.
所以,問題:
- 我應該以某種方式將控制器或動作或頁面本身標記爲異步以允許此模型初始化?
- 是否有可能將所有初始化邏輯封裝到viewmodel,而不是將其彈出到控制器?
- 該錯誤的原因是什麼?看起來像它與WebForms相關,但我使用Razor引擎。是
'Create()'應該返回Task嗎? –
Anthony
2013-03-10 18:04:18
@Anthony它應該,謝謝,修正。 – svick 2013-03-10 18:11:36
非常感謝。這對我來說非常合適。 – Anthony 2013-03-10 18:16:35