2015-06-04 44 views
-2

我已在我的項目的「內容/學生/照片」文件夾中成功上傳照片,但無法在索引視圖中顯示它們。如何在MVC中顯示圖像

這裏是我的短代碼:

型號:

public string FirstName { get; set; } 

[Display(Name = "Upload Image")] 

[NotMapped] 

public HttpPostedFileBase Photo { get; set; } 

索引視圖(用於顯示):

@Html.DisplayNameFor(model => model.FirstName) 

@Html.DisplayNameFor(model => model.Photo) 

@foreach (var item in Model) 

{ 

@Html.DisplayFor(modelItem => item.FirstName) 

    @Html.DisplayFor(modelItem => item.Photo) 

} 

什麼樣的變化,應在索引視圖中進行??

+0

你遇到了什麼問題?根據你的問題/代碼不清楚。 – JasonWilczak

+0

我想在索引視圖中顯示照片.. @ sir – Shibly

+1

您不能使用HttpPostedFileBase,我相信是用於上傳的。你需要使用該圖像的網址,並將其放入元素:[如何顯示圖像從路徑在asp.net mvc 4和剃刀視圖](http://stackoverflow.com/questions/15986980/how-to -display-image-from-path-in-asp-net-mvc-4-and-razor-view) – JasonWilczak

回答

1

試試這個。

型號:

public byte[] ImageData { get; set; } 

[HiddenInput(DisplayValue = false)] 
public string ImageMimeType { get; set; } 

查看:

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

@Html.EditorForModel() 
    <div class="editor-label">Image</div> 
     <div class="editor-field"> 
      @if (Model.ImageData == null) { 
       @:None 
      } else { 
       <img width="150" height="150" 
      src="@Url.Action("GetImage", "Product", new { Model.ProductID })" /> 
      } 
     <div>Upload new image: <input type="file" name="Image" /></div> 
    </div>   
    <input type="submit" value="Save" /> 
    @Html.ActionLink("Cancel and return to List", "Index") 
} 

控制器:

[HttpPost] 
public ActionResult Edit(Product product, HttpPostedFileBase image) { 
if (ModelState.IsValid) { 
    if (image != null) { 
     product.ImageMimeType = image.ContentType; 
     product.ImageData = new byte[image.ContentLength]; 
     image.InputStream.Read(product.ImageData, 0, image.ContentLength); 
    } 
    repository.SaveProduct(product); 
    TempData["message"] = string.Format("{0} has been saved", product.Name); 
    return RedirectToAction("Index"); 
    } else { 
     // there is something wrong with the data values 
     return View(product); 
    } 
} 


public void SaveProduct(Product product) { 
    if (product.ProductID == 0) { 
     context.Products.Add(product); 
    } else { 
     Product dbEntry = context.Products.Find(product.ProductID); 
     if (dbEntry != null) { 
     dbEntry.Name = product.Name; 
     dbEntry.Description = product.Description; 
     dbEntry.Price = product.Price; 
     dbEntry.Category = product.Category; 
     dbEntry.ImageData = product.ImageData; 
     dbEntry.ImageMimeType = product.ImageMimeType; 
     } 
    } 
    context.SaveChanges(); 
} 


public FileContentResult GetImage(int productId) { 
    Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId); 
    if (prod != null) { 
     return File(prod.ImageData, prod.ImageMimeType); 
    } else { 
     return null; 
    } 
} 

希望這有助於...