如何在视图中显示 MVC4 Directory.GetFiles
本文关键字:MVC4 Directory GetFiles 显示 视图 | 更新日期: 2023-09-27 18:34:54
我是编程初学者,我正在尝试构建一个 mvc 应用程序,该应用程序可以搜索目录并显示在视图中找到的所有目录。我在搜索时弹出一条错误消息。如果有人告诉我我做错了什么或指出我正确的方向,我们将不胜感激。
错误消息是这样的:
> The view 'C:'Users'carrick'Downloads' or its master was not found or
> no view engine supports the searched locations. The following
> locations were searched:
> ~/Views/DirectorySearch/C:'Users'carrick'Downloads.aspx
> ~/Views/DirectorySearch/C:'Users'carrick'Downloads.ascx
> ~/Views/Shared/C:'Users'carrick'Downloads.aspx
> ~/Views/Shared/C:'Users'carrick'Downloads.ascx
> ~/Views/DirectorySearch/C:'Users'carrick'Downloads.cshtml
> ~/Views/DirectorySearch/C:'Users'carrick'Downloads.vbhtml
> ~/Views/Shared/C:'Users'carrick'Downloads.cshtml
> ~/Views/Shared/C:'Users'carrick'Downloads.vbhtml
我的控制器看起来像这样
public class DirectorySearchController : Controller
{
//
// GET: /DirectorySearch/
public ActionResult Index()
{
return View();
}
public ActionResult GetDirFiles(string directorySearch)
{
//first check directorySearch is a valid path
//then get files
Directory.GetFiles(directorySearch);
ViewBag.message = directorySearch;
return View(ViewBag.message);
}
}
}
和我的观点
@{
;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>GetDirFiles</title>
</head>
<body>
<div>
<h2>Search Results</h2>
<ul>
<li>@Viewbag.message;</li>
</ul>
</div>
</body>
</html>
这一行:
return View(ViewBag.message);
您告诉它使用目录文件的名称呈现视图,因此您会收到该错误消息的原因。ViewBag 已传递到您的视图中,因此您无需自己传递它。
您很可能只想进行空参数调用
return View();
默认情况下,这将返回具有控制器中方法名称的视图。
除此之外,您不是将文件传递到视图,而是传递路径。您将需要执行类似操作。注意ViewBag(不是ViewBag(的情况
控制器:
ViewBag.message = string.Join(",", Directory.GetFiles(directorySearch));
视图:
<li>@ViewBag.message</li>
或者您可以在视图中编写一个简单的循环
控制器:
ViewBag.message = Directory.GetFiles(directorySearch);
视图:
@foreach(string file in ViewBag.message)
{
<li>@file</li>
}
在这一行中
return View(ViewBag.message);
将其更改为
return View();
第一个参数是视图名称。ViewBag 以环境/隐式方式传递到视图,因此您无需传递它。