在以下示例(taken from MSDN)中,作者正在從GetItemsAsync(...)
函數返回一個ViewModel,其功能類型爲Task<List<TodoItem>>
。如果我要從這樣一個函數返回一個ViewModel,比如myViewModel(即不是一個動作方法)。我會怎麼做?如何從操作方法以外的其他支持功能返回ViewModel
public class PriorityListViewComponent : ViewComponent
{
private readonly ToDoContext db;
public PriorityListViewComponent(ToDoContext context)
{
db = context;
}
public async Task<IViewComponentResult> InvokeAsync(
int maxPriority, bool isDone)
{
var items = await GetItemsAsync(maxPriority, isDone);
return View(items);
}
private Task<List<TodoItem>> GetItemsAsync(int maxPriority, bool isDone)
{
return db.ToDo.Where(x => x.IsDone == isDone &&
x.Priority <= maxPriority).ToListAsync();
}
}
UPDATE:
繼不起作用。請參閱下面的錯誤:
public class TestVCViewComponent : ViewComponent
{
public async Task<CustomViewModel> GetCustomViewModel(int ProjID)
{
CustomViewModel myViewModel = await GetFromDb();
return myViwModel;
}
//then call it:
public async Task<IViewComponentResult> InvokeAsync(int ProjID)
{
return View(GetCustomViewModel(ProjID));
}
}
查看:
@model myWebApp.Models.CustomViewModel
...Some html here....
@await Component.InvokeAsync("TestVC", new { ProjID = Model.ProjectId });
--some other html here...
錯誤:
出現InvalidOperationException:傳入的ViewDataDictionary型號產品類型「System.Threading.Tasks .Task`1 [myWebApp.Models.CustomViewModel]',但是這個ViewDataDictionary實例需要一個'myWebApp.Models.CustomViewModel'類型的模型項。
我的意見:
但是如果你看到這個MSDN article我做的幾乎是相同的,只是我使用Task<CustomViewModel>...
,而不是Task<List<TodoItem>>
該物品使用。
你問的是如何從方法中返回一個值? –
@EdPunittt編號我從Db填充它後需要返回myViewModel。我可以做人口的一部分。在函數不是動作方法的情況下,我對函數的簽名感到困惑。 – nam
我道歉,我誤解了這個問題。 –