从数据库中剃刀显示图像/ MVC3 [英] displaying image from db in Razor/MVC3
问题描述
我在分贝,它具有以下的表: - CountryID,国家或地区名称,和CountryImage
I have a table in the db, which has the following :- CountryID, CountryName, and CountryImage.
现在我想显示在索引中的图像,并在视图我有以下几点: -
Now I am trying to display the image in the index and I have the following in the View :-
<td>
@if (item.Image != null)
{
<img src="@Model.GetImage(item.Image)" alt="@item.CountryName"/>
}
然后在视图模型我有: -
and then in the ViewModel I have :-
public FileContentResult GetImage(byte[] image)
{
if (image != null)
return new FileContentResult(image, "image/jpeg");
else
{
return null;
}
}
不过,我无法看到图像正常。
However I cannot see the image properly.
我在做什么错了?
在此先感谢您的帮助和时间
Thanks in advance for your help and time
更新
行,所以我已经实现了查看以下内容: -
Ok So I have implemented the following in the View :-
<td>
@if (item.Image != null)
{
<img src="@Url.Action("GetImage", "CountryController", new { id = item.CountryID })" alt="@item.CountryName" />
}
</td>
和在CountryController: -
and in the CountryController :-
public ActionResult GetImage(int id)
{
var firstOrDefault = db.Countries.Where(c => c.CountryID == id).FirstOrDefault();
if (firstOrDefault != null)
{
byte[] image = firstOrDefault.Image;
return File(image, "image/jpg");
}
else
{
return null;
}
}
但是当我尝试调试code时,的ActionResult的getImage不被击中
but when I try to debug the code, the ActionResult GetImage is not being hit
推荐答案
两种可能性。
写一个控制器的动作,而不是它给予图片ID将返回这个图片:
Write a controller action instead which given an image id will return this image:
public ActionResult GetImage(int id)
{
byte[] image = ... go and fetch the image buffer from the database given the id
return File(image, "image/jpg");
}
和则:
<img src="@Url.Action("GetImage", "SomeController", new { id = item.Id })" alt="@item.CountryName" />
显然现在您最初的模型,你不需要图片
属性。这将随后负责该控制器动作进行检索。
Obviously now in your initial model you don't need the Image
property. This will be retrieved subsequently in the controller action responsible for that.
另一种可能性是使用数据URI方案嵌入图像为base64字符串,但它可能不是由获得广泛支持所有的浏览器:
Another possibility is to use data URI scheme to embed the images as base64 strings but it might not be widely supported by all browsers:
<img src="data:image/jpg;base64,@(Convert.ToBase64String(item.Image))" alt="@item.CountryName" />
您不需要在这种情况下,一个控制器动作的图像直接嵌入到您的标记为Base64字符串。
You don't need a controller action in this case as the images are directly embedded into your markup as base64 strings.
这篇关于从数据库中剃刀显示图像/ MVC3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!