Reputation: 37
I'm using mvc3 razor engine
from view I call function with Uri.Action which return FilecontentResult
<img src="@Url.Action("GetImg", "Controller", new { id = Model.Id })" alt="Person Image" />
Function:
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;
}
if byteArray is empty function returns null
how to know from view what returned function?
I need something like this
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>
}
Upvotes: 1
Views: 710
Reputation: 1038800
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);
}
and in your view simply:
<img src="@Url.Action("GetImg", "Controller", new { id = Model.Id })" alt="Person Image" />
or if you write a custom HTML helper to generate this <img>
tag even simpler:
@Html.PersonImage(Model.Id)
Upvotes: 1
Reputation: 1275
What's the something you want to do?
If it's show a default image, then return the default image instead of null.
If it's something more complex (say show an uploader, or different link), then add a property to your model that manages it, e.g. a PersonHasImage boolean.
Upvotes: 0