我正在使用mvc3 razor引擎</ p>
从视图中我用Uri.Action调用函数返回FilecontentResult
<img src="@Url.Action("GetImg", "Controller", new { id = Model.Id })" alt="Person Image" />
功能:
public FileContentResult GetImg(int id)
{
var byteArray = _context.Attachments.Where(x => x.Id == id).FirstOrDefault();
if (byteArray != null)
{
return new FileContentResult(byteArray.Content, byteArray.Extension);
}
return null;
}
如果byteArray为空函数返回null
如何从视图中了解返回的功能是什么?
我需要这样的东西
if(byteArray == null)
<img src="default img" alt="Person Image" />
else
{
<a class="highslide" href="@Url.Action("GetImg", "Controller", new { id = Model.Id })" id="thumb1" onclick="return hs.expand(this)">
<img src="@Url.Action("GetImg", "Controller", new { id = Model.Id })" alt="Person Image" /> </a>
}
答案 0 :(得分:1)
public ActionResult GetImg(int id)
{
var byteArray = _context.Attachments.Where(x => x.Id == id).FirstOrDefault();
if (byteArray == null)
{
// we couldn't find a corresponding image for this id => fallback to the default
var defaultImage = Server.MapPath("~/images/default.png");
return File(defaultImage, "image/png");
}
return File(byteArray.Content, byteArray.Extension);
}
在您看来简单:
<img src="@Url.Action("GetImg", "Controller", new { id = Model.Id })" alt="Person Image" />
或者如果您编写自定义HTML帮助程序以生成此<img>
标记甚至更简单:
@Html.PersonImage(Model.Id)
答案 1 :(得分:0)
你想做什么?
如果显示默认图像,则返回默认图像而不是null。
如果它更复杂(例如显示上传者或不同的链接),则将属性添加到管理它的模型,例如一个PersonHasImage布尔值。