从布局文件中的数据库渲染数据

时间:2016-11-08 10:09:23

标签: razor asp.net-core-mvc

我想在我的asp.net mvc核心项目的_layout文件中包含数据(从数据库中获取)。

情况:

_Layout page

@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'

我做错了什么?如何在布局页面中获取数据?

2 个答案:

答案 0 :(得分:1)

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

如果需要,您仍然可以使用@await Html.RenderPariantAsync并从模型中传递一些数据。

答案 1 :(得分: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")
}
相关问题