MVC3剃刀引擎
问题描述:
我使用MVC3剃刀引擎MVC3剃刀引擎
从视图我通话功能与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;
}
如果字节组是空函数返回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>
}
答
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)
答
什么是你想做的事?
如果显示的是默认图像,则返回默认图像而不是null。
如果它更复杂一些(比如显示一个上传者或不同的链接),那么在你的模型中添加一个属性来管理它,例如,一个PersonHasImage布尔值。
看到我的编辑职位 – Irakli 2012-02-27 11:25:58