【发布时间】:2017-08-10 15:56:27
【问题描述】:
我有一个Layout,其中有一个@RenderBody 部分和一个index 页面。我的索引页面有一个长时间运行的过程,我希望它无需等待DoSomeAsyncStuff 即可呈现视图。以下代码看起来接近我想要的,但问题在于我的模型在传递给视图时它的属性为空:
public ActionResult Index()
{
MyModel model = new MyModel();
Task.Run(() => DoSomeAsyncStuff(model));
return View(model);
}
private async void DoSomeAsyncStuff(MyModel model)
{
await Task.Delay(20000);
model.Name = "Something";
//Assigning other model properties
}
在我看来,我得到了NullReferenceException 和Value cannot be null 错误,这当然是因为我的模型的属性仍未填充到DoSomeAsyncStuff 方法中:
<table>
<tr>
<th colspan="3">
@Model.Products.Select(c => c.Date).FirstOrDefault()
</th>
</tr>
@foreach (var item in Model.Products)
{
<tr>
<td>
@item.Title
</td>
<td>
@item.Price
</td>
</tr>
}
</table>
【问题讨论】:
-
假设您的页面可以在没有数据的情况下以某种方式呈现,您唯一真正的选择是使用某种 Ajax 来加载您的绑定标记。例如,jQuery 的 load 函数可以解决这个问题。
标签: c# asp.net-mvc async-await