【问题标题】:Display image dynamically with ViewBag使用 ViewBag 动态显示图像
【发布时间】:2014-12-01 22:36:08
【问题描述】:

我想在同一视图中动态显示和更改图像。 所以我尝试使用代码:Use MVC 3 ViewBag to dynamically change an image

还有这个:Pass image from controller and display in a view using ViewBag in ASP.NET MVC 3

但没用。

这是我的Index.cshtml:

@using (Html.BeginForm("showFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    @Html.TextBox("ImageID")
    <input type="submit" value="ok" class="submit" />
}

<img src="@ViewBag.Foto" alt="IMAGES" />

我的HomeController.cs:

public ActionResult Index()
{
    return View();
}

public ActionResult showFile(string ImageID)
{
    var dir = Server.MapPath("/images/profile");
    var path = Path.Combine(dir, ImageID + ".jpg");
    if (System.IO.File.Exists(path))
    {
        ViewBag.Foto = path.ToString();
    }
    return RedirectToAction("Index", "Home");
}

【问题讨论】:

  • Use MVC 3 ViewBag to dynamically change an image 的可能重复项,如果一切都失败,请尝试谷歌搜索
  • 查看呈现的 HTML 并确保它是正确的。例如:&lt;img src="/images/profile/id.jpg" alt="" /&gt; 还要检查图像是否存在于位置 src 中。

标签: c# asp.net asp.net-mvc-5


【解决方案1】:

我认为您提供的代码示例存在 2 个问题。

第一个问题是您提供了图片标签的完整路径。您正在设置 ViewBag.Foto 属性,将 Server.MapPath() 的内容与图像相结合,因此生成的 img 标记将类似于:

<img src="C:\your-local-path-here\images\profiles\image.jpg" alt="IMAGES"/>

但你真正想要的是类似于:

<img src="/images/profile/image.jpg" alt="IMAGES"/>

第二个问题是您正在使用图像路径设置ViewBag 属性,然后执行重定向。当您将重定向返回到浏览器时,ViewBag 的内容不会为对 Index() 操作的下一个请求进行维护。

控制器代码因此可以更改为:

public ViewResult Index()
{
    return View();
}

[HttpPost]
public ViewResult ShowFile(string imageId)
{
    var virtualPath = string.Format("~/images/profile/{0}.jpg", imageId);

    if (System.IO.File.Exists(Server.MapPath(virtualPath)))
    {
        ViewBag.Foto = VirtualPathUtility.ToAbsolute(virtualPath);
    }
    return View("Index");
}

此外,您无需在表单中指定new { enctype = "multipart/form-data" }(请参阅What does enctype='multipart/form-data' mean?)。

【讨论】:

  • 你是对的!!应该是 "return View("Index");"!!非常感谢:)
【解决方案2】:

那是因为 Server.MapPath 会返回图片的物理路径,这不是你想要的。您将需要服务器相对路径 (/images/profile/xxxxx)。

【讨论】:

  • 你是这个意思吗? >> 在控制器中:ViewBag.Foto = "~/images/profile/"+ImageID+".jpg";
  • 有我的新代码:my controller, my view Tempdata was Displayed "ok"...
【解决方案3】:

我会使用“ViewBag.Foto”而不是“@ViewBag.Foto”。

剃刀语法将在视图中使用@符号,但在控制器中不使用。

【讨论】:

  • 对不起,那是我的错……但代码原是“ViewBag.Foto = path.ToString();”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-23
  • 2015-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多