首页 > 解决方案 > 在 .NET Core 2+ 中以 _Layout 显示模型并创建收藏夹列表

问题描述

第一次发帖。

我对编程很陌生,我正在尝试创建一个网站来容纳我构建的网络应用程序。我目前有一个模型、视图和控制器来投影我的 Apps 表的内容。这些应用程序托管在其他地方,因此出现在下面屏幕截图中的图块只是链接到其他位置。我想包括一种在抽屉中显示最近使用的应用程序的方法(代码位于 _Layout 中)。

_布局抽屉:

_布局抽屉

我想首先在 _Layout 抽屉中显示任何模型数据。如果我只是将我的应用程序视图代码放入 _Layout,如下所示:

@_Layout, located beneath navbar code and above RenderBody()@
@model IEnumerable<Apps>
<div id="footerSlideContainer">
    <div id="footerSlideButton"></div>
    <div id="footerSlideContent">
        <div id="footerSlideText">

            <div class="parenttile">

                @foreach (var Apps in Model)
                {
                    <a href="http://@Apps.AppLink" target="_blank">
                        <div class="tile">
                            <div></div>
                            <div class="tilemid">
                                <div></div>
                                <div>
                                    <img class="tileimage" src="@Apps.AppImage" alt="@Apps.AppName" />
                                </div>
                                <div></div>
                            </div>
                            <div class="tilebot">
                                @Apps.AppName
                            </div>
                        </div>
                    </a>
                }
            </div>
            <h3>Recently Used Apps</h3>
            <p>This section will store all of your most recently used apps. It stays on the screen until you click the drawer icon.</p>
        </div>
    </div>
</div>

...我在@foreach 行的调试中收到以下错误:NullReferenceException:对象引用未设置为对象的实例。.net 核心。我在这里研究了该错误:什么是 NullException 错误以及如何修复它?

  1. 我了解动作方法出现在模型显示之前。如果我要使用上面的代码,我会假设我需要将模型注入到操作方法中——但是,_layout 是否有控制器?
  2. 我在这里研究过:ASP MVC Razor Pass model to view。这看起来是最接近的解决方案,但希望有人带我完成它。
  3. 最后,我注意到我可以在 ASP.NET Core 中使用 ViewComponent ViewComponent。我可以使用一些帮助来实施此解决方案。

这些解决方案中的哪一个最有效/最有效?

然后是创建收藏夹的问题。我认为这更简单一些,因为此显示最近查看的项目包含我认为我需要的所有信息。

感谢您的帮助 - 我在下面包含我的模型和控制器代码:

模型:

    public class Apps
{

    public int AppID { get; set; }
    public string AppName { get; set; }
    public string AdGroup { get; set; }
    public string AppDescription { get; set; }
    public string AppLink { get; set; }
    public string AppImage { get; set; }

}

控制器(在我转移到 db 之前,暂时使用硬编码的虚拟数据)

public class AppsController : Controller
{
    private List<Apps> _apps;

    public AppsController()
    {
        _apps = new List<Apps>();

        //creating test Apps model 
        _apps.Add(new Apps
        {
            AppID = 1,
            AppName = "Test App 1",
            AdGroup = "Group 1",
            AppDescription = "First test app.",
            AppLink = "www.google.com",
            AppImage = "/images/image1.png"

        }); //et al
    }


    public IActionResult Index()
    {
        return View(_apps);
    }
}

标签: c#.net.net-coreasp.net-core-2.0dotnet-core-pack

解决方案


推荐阅读