如何显示在MVC的图像 [英] How to display images in MVC
本文介绍了如何显示在MVC的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经上传照片成功我的项目内容/学生/照片文件夹,但在索引视图无法显示出来。
I have uploaded photos successfully in "Content/Student/Photo" folder of my project but can't display them in Index view.
这是我的短code:
型号:
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)
}
什么样的变化,应在索引视图中所做?
what changes should be made in the Index view??
推荐答案
试试这个。
型号:
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;
}
}
希望这有助于...
Hope this helps...
这篇关于如何显示在MVC的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文