Skip to main content
 首页 » 编程设计

c#之使用 ViewBag 动态显示图像

2024年08月12日39webabcd

我想在同一 View 中动态显示和更改图像。 所以我尝试使用代码: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"); 
} 

请您参考如下方法:

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

第一个 问题是您提供了图像标签的完整路径。您正在将 Server.MapPath() 的内容与图像结合设置 ViewBag.Foto 属性,因此生成的 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() 操作的请求保留。

Controller 代码因此可以更改为:

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? )。