2016-11-08 67 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") 
}