I am using EF 4.1 Code First and for the sake of simplicity, let's say I have the following Entity class:
public class Person { public int Id { get; set; } public string Name { get; set; } public Byte[] Image { get; set; } }
I have managed to create a working Create View that allows the Addition of a Person object into the Database.
But when I come to display the details for a Person, I get stuck on displaying the image. After doing some research, I have the following:
// To convert the Byte Array to the author Image public FileContentResult getImg(int id) { byte[] byteArray = DbContext.Persons.Find(id).Image; return byteArray != null ? new FileContentResult(byteArray, "image/jpeg") : null; }
And in the View where I am attempting to list the Person details, I have the following to get the Image to display:
<img src="@Html.Action("getImg", "Person", new { id = item.Id })" alt="Person Image" />
However the above is not working, my image source [src] attribute returns empty.
//ImageConverter Class convert Image object to Byte Array. byte[] bytes = (byte[])(new ImageConverter()). ConvertTo(img, typeof(byte[])); //Convert Byte Array to Image and display in PictureBox.
A view is an HTML template with embedded Razor markup. Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET Core MVC, views are .cshtml files that use the C# programming language in Razor markup.
ASP.NET MVC 5 for Beginners Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.
What is Razor? Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages. Server-based code can create dynamic web content on the fly, while a web page is written to the browser.
There's an even easier way of doing this if you already happen to have the image loaded in your model:
<img src="data:image;base64,@System.Convert.ToBase64String(Model.Image)" />
Doing this way you do not need to go to the server again just to fetch the image byte[]
from the database as you're doing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With