2016-11-30 38 views
0

在以下示例(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>>該物品使用。

+0

你問的是如何從方法中返回一個值? –

+0

@EdPunittt編號我從Db填充它後需要返回myViewModel。我可以做人口的一部分。在函數不是動作方法的情況下,我對函數的簽名感到困惑。 – nam

+0

我道歉,我誤解了這個問題。 –

回答

0

這就是你如何寫一個異步方法返回一個自定義類型:

public async Task<CustomViewModel> GetCustomViewModel() 
{ 
    CustomViewModel myViewModel = await GetFromDb(); 
    return myViwModel; 
} 

然後調用它:

var customViewModel = await GetCustomViewModel(); 
+0

您的建議可能會接近。但我仍然遇到錯誤。我在上面的帖子中添加了一個UPDATE部分來解釋我在做什麼。 – nam

+0

我想你應該添加await(不知道在哪裏),我只是看了一些關於它的pluralsight教程。 – Alexan

+0

https://www.pluralsight.com/courses/aspdotnet-core-fundamentals#invite-modal – Alexan

2

在你更新代碼,你必須等待GetCustomViewModel調用

更換

return View(GetCustomViewModel(ProjID)); 

return View(await GetCustomViewModel(ProjID)); 
相關問題