首页 > 解决方案 > 创建模型以保存 Path.Combine 数组的结果

问题描述

我的开发环境是 VS19、ASP .Net Core Razor (non-MVC) 3.1 Pages 和 Entity Framework Core。

我的模型文件夹中有以下类/模型,它有一个属性:

````
public class FilesObject
{
    public string[] Files { get; set; } = new string[1000];
}

在我的 index.cs 文件的 OnGet() 处理程序中,我编写了以下代码以返回一个数组,其中包含指定目录 (wwwroot\documents) 中的文件列表

 public class IndexModel : PageModel
    {
        private readonly ApplicationDbContext _context;
        private readonly IWebHostEnvironment _hostingEnvironment;

        public IndexModel(ApplicationDbContext context, IWebHostEnvironment hostingEnvironment)
        {
            _context = context;
            _hostingEnvironment = hostingEnvironment;
        }

        [BindProperty]
        public FilesObject FilesObject { get; set; }

        public IActionResult OnGet() 
        {

            var webRootPath = _hostingEnvironment.WebRootPath;
            var docsPath = Path.Combine(webRootPath, "documents");
            FilesObject = Directory.GetFiles(docsPath);

            return Page();
        }
    }

我收到以下错误:错误 CS0029 无法在此行上将类型字符串隐式转换为 Models.FilesObject:

FilesObject = Directory.GetFiles(docsPath);

我最初尝试做这样的事情:

var DocumentInfo = Path.Combine(webRootPath, "documents");

这很好用,但是,我无法将 DocumentInfo 返回到我的 index.cshtml 页面以对其执行任何操作,例如 ForEach 循环。

我明白错误告诉我什么,我只是不知道如何解决它。

任何帮助表示赞赏。提前感谢您的宝贵时间。

标签: c#asp.netasp.net-corerazorrazor-pages

解决方案


Error CS0029 Cannot implicitly convert type string to Models.FilesObject on this line:

Directory.GetFiles returns string[],so you need to change like below:

FilesObject.Files = Directory.GetFiles(docsPath);

Before using it,you need to initialize the FilesObject.Here is a working demo like below:

1.Index.cshtml:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

@foreach(var data in Model.FilesObject.Files)
{
    <div>
        @data;
    </div>

}

2.Index.cshtml.cs:

public class IndexModel : PageModel
{
    private readonly IWebHostEnvironment _hostingEnvironment;

    public IndexModel( IWebHostEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    [BindProperty]
    public FilesObject FilesObject { get; set; }

    public IActionResult OnGet()
    {
        FilesObject = new FilesObject() { };//need to add this line to initialize the model
        var webRootPath = _hostingEnvironment.WebRootPath;
        var docsPath = Path.Combine(webRootPath, "documents");
        FilesObject.Files = Directory.GetFiles(docsPath);

        return Page();
    }
}

Result: enter image description here

enter image description here


推荐阅读