当我尝试从其中的文件夹传递所有文件时,MVC中的Bootstrap图像滑块中断 [英] Bootstrap image slider in MVC breaks when I try to pass all files from folder in it
问题描述
@{
ViewBag.Title = "GalerijaIndex";
Layout = "~/Views/Shared/_GalerijaLayout.cshtml";
}
<div id="mycarousel" class="carousel slide" data-ride="carousel" style="margin-top: -15px">
<ol class="carousel-indicators">
<li data-target="#mycarousel" data-slide-to="0" class="active"></li>
<li data-target="#mycarousel" data-slide-to="1"></li>
<li data-target="#mycarousel" data-slide-to="2"></li>
</ol>
<div class="carousel-inner" role="listbox">
<div class="item active">
<img src="~/Content/First/Music1.jpg" />
</div>
@{
string source = "~/Content/Images/";
string[] fileEntries = Directory.GetFiles(source);
foreach (var i in fileEntries)
{
<div class="item">
<img src="~/Content/Images/@{Path.GetFileName(i)}" />
</div>
}
}
}
<a class="left carousel-control" href="#mycarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Prethodna</span>
</a>
<a class="right carousel-control" href="#mycarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Slijedeća</span>
</a>
</div>
目标是填充滑块动力与~Content / Images /文件夹中的所有图像一起使用,以便显示它们。所有的逻辑都在View上,但我无法弄清楚为什么我会收到500错误。
我尝试了什么:
我尝试过我所知道的,但我不知道出了什么问题。其他一切都很好。我已经通过ViewBag从控制器尝试传递值,同样的事情;
The goal is to populate slider dynamically with all images in "~Content/Images/" folder, so that it can display them. All the logic is here on View, yet I can't figure out why I'm getting 500 error.
What I have tried:
I've tried what I known, but I have no idea what is wrong. Everything else works fine. I have tried pass value to it via ViewBag from controller, same thing;
推荐答案
你还没有告诉我们错误是什么,但是猜测一下,它可能来自这两行:
You still haven't told us what the error is, but at a guess, it probably comes from these two lines:
string source =〜/ Content / Images /;
string [] fileEntries = Directory.GetFiles(source);
string source = "~/Content/Images/";
string[] fileEntries = Directory.GetFiles(source);
Directory.GetFiles
方法预期文件夹的物理路径。您正在传递与应用程序相关的虚拟路径。由于 GetFiles
方法对ASP.NET应用程序一无所知,因此很可能会得到 DirectoryNotFoundException
。
要解决此问题,您需要将虚拟路径映射到物理路径:
The Directory.GetFiles
method expects the physical path to the folder. You are passing in an app-relative virtual path. Since the GetFiles
method knows nothing about ASP.NET applications, you will most likely get a DirectoryNotFoundException
.
To fix that, you need to map the virtual path to a physical path:
string source = "~/Content/Images/";
string physicalPath = System.Web.Hosting.HostingEnvironment.MapPath(source);
string[] fileEntries = Directory.GetFiles(physicalPath);
注意: 这种代码实际上属于控制器,而不是视图。
NB: This sort of code really belongs in the controller, not the view.
这篇关于当我尝试从其中的文件夹传递所有文件时,MVC中的Bootstrap图像滑块中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!