Upload and display image in MVC application.

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.

public class ContentViewModel

{

        public int ID { get; set; }       

        public string Title { get; set; }

        public string Description { get; set; }       

        [AllowHtml]       

        public string Contents { get; set; }

        public byte[] Image { get; set; }

}

Step 2: Create Action Method in Controller class .

public ActionResult Create()

{

     return View();

}

Step 3: Create View

@using (Html.BeginForm("Create","Content", FormMethod.Post, new { enctype ="multipart/form-data" }))

{
   <input type="file" name="ImageData" id="ImageData" onchange="fileCheck(this);" />
}

Step 4: Submit form

[Route("Create")]

[HttpPost]

public ActionResult Create(ContentViewModel model)

{

    HttpPostedFileBase file = Request.Files["ImageData"];

    ContentRepository service = new ContentRepository();

    int i = service.UploadImageInDataBase(file, model);

    if (i == 1)

    {

         return RedirectToAction("Index");

    }

    return View(model);

}

Step 5

private readonly DBContext db = new DBContext();

public int UploadImageInDataBase(HttpPostedFileBase file, ContentViewModel          contentViewModel)

{

        contentViewModel.Image = ConvertToBytes(file);

        var Content = new Content

        {

            Title = contentViewModel.Title,

            Description = contentViewModel.Description,

            Contents = contentViewModel.Contents,

            Image = contentViewModel.Image

        };

        db.Contents.Add(Content);

        int i = db.SaveChanges();

        if (i == 1)

        {

            return 1;

        }

        else

        {

            return 0;

        }

}

public byte[] ConvertToBytes(HttpPostedFileBase image)

{

      byte[] imageBytes = null;

     BinaryReader reader = new BinaryReader(image.InputStream);

     imageBytes = reader.ReadBytes((int)image.ContentLength);

    return imageBytes;

}

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

public ActionResult Index()

{

    var content = db.Contents.Select(s => new

    {

        s.ID,

        s.Title,

        s.Image,

        s.Contents,

        s.Description

      });

      List<ContentViewModel> contentModel = content.Select(item => new ContentViewModel()

      {

            ID = item.ID,

            Title = item.Title,

            Image = item.Image,

            Description = item.Description,

            Contents = item.Contents

        }).ToList();

       return View(contentModel);

 }

Step 7: Set the Retrieve Image action with ID

<td>

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

</td>

public ActionResult RetrieveImage(int id)

{

            byte[] cover = GetImageFromDataBase(id);

            if (cover != null)

            {

                return File(cover, "image/jpg");

            }

            else

            {

                return null;

            }

}

public byte[] GetImageFromDataBase(int Id)

{

            var q = from temp in db.Contents where temp.ID == Id select temp.Image;

            byte[] cover = q.First();

            return cover;

}

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.

<script src="~/ckeditor/ckeditor.js"></script>
<script src="~/ckeditor/adapters/jquery.js"></script>

Step 2

@Html.TextAreaFor(model => model.Contents, new { @class = "ckeditor", placeholder = "Content" })

Step 3: Allow a HTML attribute in your model like this:

[AllowHtml]
[Required]
public string Contents { get; set; }

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>").

Up Next
    Ebook Download
    View all
    Learn
    View all