c# - 创建模型以保存 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 循环。
我明白错误告诉我什么,我只是不知道如何解决它。
任何帮助表示赞赏。提前感谢您的宝贵时间。
解决方案
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();
}
}
推荐阅读
- azure-ad-b2c - Azure 广告 b2c 帐户锁定
- scala - Scala 隐式扩展接口
- reactjs - 无法在网站上显示图像 Webpack React-dom 意外语法
- python - 它说“TypeError:__init__() 需要 4 个位置参数,但给出了 5 个”,但我不明白为什么(Python3)
- python - 程序获取数字 1-1000 的列表,将它们反转,将它们放入一个文件(称为 my_file)并将它们打印回 my_file
- python - 使用 Python 和 Tesseract OCR 解决验证码
- python - 国家和人口
- python - 无法将 get 方法与 Tkinter Text Widget 一起使用
- c# - ASP.NET Identity 的 UserManager 是否需要关闭或处置?
- python-3.x - 类中的函数需要类中另一个函数的输入