Joh*_*ann 11 razor c#-4.0 asp.net-mvc-3
我在db中有一个表,它有以下内容: - CountryID,CountryName和CountryImage.
现在我试图在索引中显示图像,我在视图中有以下内容: -
<td>
@if (item.Image != null)
{
<img src="@Model.GetImage(item.Image)" alt="@item.CountryName"/>
}
Run Code Online (Sandbox Code Playgroud)
然后在ViewModel我有: -
public FileContentResult GetImage(byte[] image)
{
if (image != null)
return new FileContentResult(image, "image/jpeg");
else
{
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
但是我无法正确看到图像.
我究竟做错了什么?
在此先感谢您的帮助和时间
UPDATE
好的,我在视图中实现了以下内容: -
<td>
@if (item.Image != null)
{
<img src="@Url.Action("GetImage", "CountryController", new { id = item.CountryID })" alt="@item.CountryName" />
}
</td>
Run Code Online (Sandbox Code Playgroud)
并在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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试调试代码时,ActionResult GetImage没有被命中
Dar*_*rov 18
两种可能性.
写一个控制器动作,而给定一个图像id将返回此图像:
public ActionResult GetImage(int id)
{
byte[] image = ... go and fetch the image buffer from the database given the id
return File(image, "image/jpg");
}
Run Code Online (Sandbox Code Playgroud)
然后:
<img src="@Url.Action("GetImage", "SomeController", new { id = item.Id })" alt="@item.CountryName" />
Run Code Online (Sandbox Code Playgroud)
显然,现在在您的初始模型中,您不需要该Image属性.随后将在负责该操作的控制器操作中检索此项.
另一种可能性是使用数据URI方案将图像嵌入为base64字符串,但它可能并未得到所有浏览器的广泛支持:
<img src="data:image/jpg;base64,@(Convert.ToBase64String(item.Image))" alt="@item.CountryName" />
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您不需要控制器操作,因为图像直接作为base64字符串嵌入到标记中.
| 归档时间: |
|
| 查看次数: |
17492 次 |
| 最近记录: |