Reputation: 35
I build form to save Images in database with other fields like News Title. when i want to retrieve all the fields of the DB and see it, the code i used is work, but when image file is loaded to db if image not loaded it will stop and not work, And not all news have image that's in my project
<table class="table table-responsive table-bordered table-striped table-hover ">
<tr>
<th>
@Html.DisplayNameFor(model => model.NewsTitle)
</th>
<th>
@Html.DisplayNameFor(model => model.NewsImage)
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.NewsTitle)
</td>
<td>
@{
var base64 = Convert.ToBase64String(item.NewsImage);
var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);
}
<img src='@imgsrc' style="max-width:100px;max-height:100px" />
</td>
</tr>
}
</table>
Upvotes: 1
Views: 2515
Reputation: 23200
And not all news have image that's in my project
I'm supposing that if no image is available then the NewsImage
property is probably null
.
So you can write this code:
@{
var imgsrc = "url_to_your_default_image"; // useful when image is not available
if(item.NewsImage != null)
{
var base64 = Convert.ToBase64String(item.NewsImage);
imgsrc = string.Format("data:image/jpg;base64,{0}", base64);
}
<img src='@imgsrc' style="max-width:100px;max-height:100px" />
}
Upvotes: 2