ASP .NET MVC中常用的数据类型用于图像是byte数组。我们可以在模型类中将图像的属性设为byte[]类型,然后在视图中使用HtmlHelper将其以图片的形式呈现。例如:
模型类:
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
}
视图:
@model Product
@{
Layout = null;
}
Display Image
@Model.Name
控制器:
public class ProductController : Controller
{
private readonly MyDbContext db = new MyDbContext();
// GET: Product/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
// Get Image
public ActionResult GetImage(int id)
{
Product product = db.Products.Find(id);
if (product != null && product.ImageData != null)
{
return File(product.ImageData, product.ImageMimeType);
}
return null;
}
}