2016-11-08 69 views
0

我想在我的asp.net mvc核心項目的_layout文件中包含數據(從數據庫中提取)。從佈局文件中的數據庫呈現數據

現狀:

_layout頁

@if (SignInManager.IsSignedIn(User)) 
{ 
    Html.Action("Modules", "Layout") 
} 

控制器/ LayoutController.cs

using Microsoft.AspNetCore.Mvc; 

namespace project.Controllers 
{ 
    public class LayoutController : Controller 
    { 
     ... 

     public ActionResult Modules() 
     { 
      ///Return all the modules 
      return PartialView("_Modules", moduleAccess.ToList()); 
     } 
    } 
} 

查看/共享/ _Modules.cshtml

@model IEnumerable<project.Models.Module> 
<div class="two wide column"> 
<div class="ui menu" id="modules"> 
    @foreach (var item in Model) 
    { 
     <a class="item"> 
      @Html.DisplayFor(modelItem => item.Name) 
     </a> 
    } 
</div> 

當去的網頁我得到以下錯誤:

'IHtmlHelper<dynamic>' does not contain a definition for 'Action' and the best extension method overload 'UrlHelperExtensions.Action(IUrlHelper, string, object)' requires a receiver of type 'IUrlHelper' 

我在做什麼錯?我怎樣才能獲得佈局頁面中的數據?

回答

1

在ASP.NET Core而不是Html.Action中使用View Components@await Component.InvoceAsync

如果需要,您仍然可以使用@await Html.RenderPariantAsync並從該模型傳遞一些數據。

+0

Thxs的Dawid,它像一個沙姆沙伊赫! – Wouter

0

解視圖分量

ViewComponents/ModuleListViewComponent.cs

using Microsoft.AspNetCore.Mvc; 
using System.Threading.Tasks; 

namespace ViewComponents 
{ 
    public class ModuleListViewComponent : ViewComponent 
    { 
     ... 

     public async Task<IViewComponentResult> InvokeAsync() 
     { 
      return View(moduleAccess.ToList()); 
     }  
    } 
} 

查看/共享/組件/ ModuleList/Default.cshtml

@model IEnumerable<project.Models.AdminModels.Module> 

<div class="two wide column"> 
<div class="ui left vertical labeled icon menu stackable" id="modules"> 
    @foreach (var module in Model) 
    { 
     <a class="item"> 
      @module.Name 
     </a> 
    } 
</div> 
</div> 

查看/共享/ _Layout.cshtml

@if (SignInManager.IsSignedIn(User)) 
{ 
    @await Component.InvokeAsync("ModuleList") 
}