Upload and display image in MVC application

In this article we will learn how to upload and display an image in MVC.

1. Upload and display image in MVC application.

There is a very simple way to store images in database from MVC application.

Step 1: First we create a class in model folder.

  1. public class ContentViewModel  
  2. {  
  3.     public int ID { get; set; }  
  4.     public string Title { get; set; }  
  5.     public string Description { get; set; }  
  6.     [AllowHtml]  
  7.     public string Contents { get; set; }  
  8.     public byte[] Image { get; set; }  
  9. }  
Step 2: Create Action Method in Controller class .
  1. public ActionResult Create()  
  2. {  
  3.      return View();  
  4. }  
Step 3: Create View
  1. @using (Html.BeginForm("Create","Content", FormMethod.Post, new { enctype ="multipart/form-data" }))  
  2. {   
  3.    <input type="file" name="ImageData" id="ImageData" onchange="fileCheck(this);" />  
  4. }  
Step 4: Submit form
  1. [Route("Create")]  
  2. [HttpPost]  
  3. public ActionResult Create(ContentViewModel model)  
  4. {  
  5.     HttpPostedFileBase file = Request.Files["ImageData"];  
  6.     ContentRepository service = new ContentRepository();  
  7.     int i = service.UploadImageInDataBase(file, model);  
  8.     if (i == 1)  
  9.     {  
  10.          return RedirectToAction("Index");  
  11.     }  
  12.     return View(model);  
  13. }  
Step 5
  1. private readonly DBContext db = new DBContext();  
  2. public int UploadImageInDataBase(HttpPostedFileBase file, ContentViewModel contentViewModel)  
  3. {  
  4.     contentViewModel.Image = ConvertToBytes(file);  
  5.     var Content = new Content  
  6.     {  
  7.        Title = contentViewModel.Title,  
  8.        Description = contentViewModel.Description,  
  9.        Contents = contentViewModel.Contents,  
  10.        Image = contentViewModel.Image  
  11.     };  
  12.     db.Contents.Add(Content);  
  13.     int i = db.SaveChanges();  
  14.     if (i == 1)  
  15.     {  
  16.         return 1;  
  17.     }  
  18.     else  
  19.     {  
  20.         return 0;  
  21.     }  
  22. }  
  23. public byte[] ConvertToBytes(HttpPostedFileBase image)  
  24. {  
  25.      byte[] imageBytes = null;  
  26.      BinaryReader reader = new BinaryReader(image.InputStream);  
  27.      imageBytes = reader.ReadBytes((int)image.ContentLength);  
  28.      return imageBytes;  
  29. } 

Step 6: Display an image form database on view. Here we display the content and image from the database.

  1. public ActionResult Index()  
  2. {  
  3.     var content = db.Contents.Select(s => new  
  4.     {  
  5.         s.ID,  
  6.         s.Title,  
  7.         s.Image,  
  8.         s.Contents,  
  9.         s.Description  
  10.       });  
  11.       List<ContentViewModel> contentModel = content.Select(item => new ContentViewModel()  
  12.       {  
  13.             ID = item.ID,  
  14.             Title = item.Title,  
  15.             Image = item.Image,  
  16.             Description = item.Description,  
  17.             Contents = item.Contents  
  18.         }).ToList();  
  19.        return View(contentModel);  
  20. }  
Step 7: Set the Retrieve Image action with ID

  1. <td>  
  2.      <img src="/Content/RetrieveImage/@item.ID" alt="" height=100 width=200 />  
  3. </td>  

  1. public ActionResult RetrieveImage(int id)  
  2. {  
  3.     byte[] cover = GetImageFromDataBase(id);  
  4.     if (cover != null)  
  5.     {
  6.         return File(cover, "image/jpg");  
  7.     }  
  8.     else  
  9.     {
  10.         return null;  
  11.     }  
  12. }  
  13. public byte[] GetImageFromDataBase(int Id)  
  14. {  
  15.     var q = from temp in db.Contents where temp.ID == Id select temp.Image;  
  16.     byte[] cover = q.First();  
  17.     return cover;  
  18. }  

Insert Image 
 
Display Image

2. How to use ckeditor in MVC

If you want to use ckeditor in ASP.NET MVC then check the official CKEditor.NET Control. And download it from CKEditor and unzip this folder. After you download the installation package, copy the ckeditor folder and paste it into our solution.

Step 1: Set a reference for ckeditor.js and jquery.js in the view.

  1. <script src="~/ckeditor/ckeditor.js"></script>  
  2. <script src="~/ckeditor/adapters/jquery.js"></script>  
Step 2
  1. @Html.TextAreaFor(model => model.Contents, new { @class = "ckeditor", placeholder = "Content" })   
Step 3: Allow a HTML attribute in your model like this:
  1. [AllowHtml]  
  2. [Required]  
  3. public string Contents { getset; }  
If you are not AllowHtml attribute run time exception. A potentially dangerous Request.Form value was detected from the client (Contents="<p>Content Here</p>").