在我的代码中显示图像时找不到错误

问题描述:

嗨我从我之前的一个Web应用程序获取了此代码。我只是复制并粘贴到一个新的,但图像不显示在新的网站。我甚至输入代码来显示路径,它显示ok,显示id,它显示ok以及Products中的所有属性,它们都显示ok,但图像不显示。当F5我的应用程序的网站运行良好。但是当img无法加载时,它只显示小图标,而不是图像。当从浏览器使用检查器时,src atribute具有正确的图像路径。 我找不到什么是错 这里是代码在我的代码中显示图像时找不到错误

这是分类类别

namespace Mysite.Models 
{ 
    public class Category 
    { 
     //[ScaffoldColumn(false)] 
     public int CategoryID { get; set; } 

     [Display(Name = "Category Name")] 
     public string CategoryName { get; set; } 

     //[Display(Name = "Product Description")] 
     public string Description { get; set; } 

     public string ImagePath { get; set; } 

     public virtual ICollection<Product> Products { get; set; } 

    } 

} 

,这是产品类别

namespace Mysite.Models 
{ 
    public class Product 
    { 
     //[ScaffoldColumn(false)] 
     public int ProductID { get; set; } 

     [Required, StringLength(100), Display(Name = "Product Name")] 
     public string ProductName { get; set; } 

     [Required, StringLength(10000), Display(Name = "Product Description"), DataType(DataType.MultilineText)] 
     public string Description { get; set; } 

     public string ImagePath { get; set; } // Here is the image path that I want to show   

     public int? CategoryID { get; set; } 

     public virtual Category Category { get; set; } 
    } 
} 

这是有一个方法浏览的CategoryController那公司产品种类齐全

namespace Mysite.Controllers 
{ 
    public class CategoriesController : Controller 
    { 
       private ProductContext db = new ProductContext(); 

       public ActionResult Browse(string categories) 
     { 
      var categoriaModel = db.Categories.Include("Products") 
       .SingleOrDefault(c => c.CategoryName == categories); 
      return View(categoriaModel);/*(db.Categories.C)*/ 

     } 

一第二,这是测试是否所有我想在浏览器中显示的简单视图,实际上得到显示

@model Mysite.Models.Category 

@{ 
    ViewBag.Title = "Browse"; 
} 

<h2>Browse</h2> 
@foreach(var item in Model.Products) { 

<p>@item.ProductName , @item.ProductID , @item.ImagePath</p> 

<img src="@item.ImagePath"/> 

} 

,但是这是它真实地反映了

Horizontal Faux Wood , 1 , Content/ProductImages/woodblind2.jpg /*small non-loaded picture icon here*/ 

Horizontal Real Wood , 2 , Content/ProductImages/woodblinds1.jpg /*small non-loaded picture icon here*/ 

Aluminium mini blinds , 10 , Content/ProductImages/aluminiumminiblind.jpg /*small non-loaded picture icon here*/ 

此相同的代码,我有它在另一现场工作。 我仔细检查了图片文件夹,路线,一切都OK

更改它以这样的:

<img src="@Url.Content("~/" + item.ImagePath)"/> 
+0

这是一个有效的工具。但不明白为什么这个,而不是其他人是否可以(显然) – shark6552

试试这个

<img src= "@Url.Content(item.ImagePath)" alt="Image" /> 
+0

我现在远离我的电脑,但我想这会工作但是这与src“@ item.ImagePath”有什么不同? – shark6552

你缺少个/ImagePath之前指定root,我宁愿将string变量从另一个""中取出。这就是我的方法呢

<img src="~/@item.ImagePath" />

本质上~符号,您可以相对于根路径引用文件。