我有一个Layout
与 @RenderBody
部分和 index
页。我的索引页面有一个长时间运行的进程,我希望它渲染 View 而不等待 DoSomeAsyncStuff
。下面的代码看起来很接近我想要的,但问题是我的模型在传递给 View 时它的属性为空:
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>
最佳答案
您尚未展示您的模型,因此这主要是伪代码。首先,将长时间运行的内容移至另一个操作:
public ActionResult Index()
{
var model = new MyModel();
return View(model);
}
public async Task<ActionResult> DoSomeAsyncStuff()
{
var model = new MyModel();
await Task.Delay(20000);
model.Name = "Something";
//Assigning other model properties
return PartialView("_InnerView", model);
}
模型绑定(bind)的所有内容都应该位于分部 View 中(我在这里称之为_InnerView.cshtml
)。父 View 应该只有一个占位符或加载小部件,其中模型绑定(bind)标记当前所在:
<div id="load-with-ajax">
Please wait. Loading...
</div>
然后,在页面中的某个位置,在您的 jQuery 引用之后(我假设您正在使用 jQuery 或者愿意),添加如下内容:
<script>
$(function(){
$('#load-with-ajax').load('@Url.Action("DoSomeAsyncStuff")');
});
</script>
关于c# - 如何运行方法而不等待长时间运行的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45605708/