Details And User Picture In MVC 5

Today I am going to write something about how we can add CRUD views to our site along with a picture, and show them at views. Here I will go step by step. I am using VS2015 MVC 5.
  1. Open your Visual studio and create a new project. Please take care of the picture and watch it carefully.

    create 

    Next follow this picture.

    mvc
Now click on the Models folder and add a new class, name it File (for our pictures purpose). Paste the following code in it.
  1. public class File  
  2. {  
  3.         public int FileId { getset; }  
  4.         [StringLength(255)]  
  5.         public string FileName { getset; }  
  6.         [StringLength(100)]  
  7.         public string ContentType { getset; }  
  8.         public byte[] Content { getset; }  
  9.         public FileType FileType { getset; }  
  10.         public int UserId { getset; }  
  11.         public virtual User User { getset; }  

Click again on models folder and add another class, name it FileType.cs, paste this code on it.
  1. public enum FileType  
  2. {  
  3.     Avatar = 1, Photo  

Now add another class to the models folder, name it User.cs (Image) and paste the following code on it.

Note: this is the class in which we define our data context. 
  1. public class  User  
  2.    {  
  3.         
  4.        public int ID { getset; }  
  5.        [Required]  
  6.        public string Name { getset; }  
  7.        public string LastName { getset; }  
  8.        public string Province { getset; }  
  9.        public string District { getset; }  
  10.        public byte[] Photo { getset; }  
  11.       [Required]  
  12.        public string Group{ getset; }  
  13.        [Required]  
  14.        public string RH { getset; }  
  15.        [Required]  
  16.        public string Location { getset; }  
  17.       [Required]  
  18.        public string Mobile { getset; }  
  19.        public virtual ICollection<File> Files { getset; }  
  20.    }  
  21.   
  22.    public class UserDBContext : DbContext  
  23.    {  
  24.        public DbSet<User> Users { getset; }  
  25.        public DbSet<File> Files { getset; }  
  26.    } 
Yes! that was our modeling. Now go to the controllers folder and a new controller with views. Add this code on it. Please remember that if something went wrong with the code change your database connection string name and database name can be found in web.config file.
  1. public class UsersController : Controller  
  2.    {  
  3.        private UserDBContext db = new UserDBContext();  
  4.   
  5.        // GET: Users  
  6.        public ActionResult Index()  
  7.        {  
  8.                    return View(users);  
  9.        }  
  10.   
  11.        // GET: Users/Details/5  
  12.        public ActionResult Details(int? id)  
  13.        {  
  14.            if (id == null)  
  15.            {  
  16.                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  17.            }  
  18.            User user = db.Users.Include(s => s.Files).SingleOrDefault(s => s.ID == id);  
  19.              
  20.            if (user == null)  
  21.            {  
  22.                return HttpNotFound();  
  23.            }  
  24.            return View(user);  
  25.        }  
  26.   
  27.        // GET: Users/Create  
  28.        public ActionResult Create()  
  29.        {  
  30.            return View();  
  31.        }  
  32.   
  33.        // POST: Users/Create  
  34.        [Authorize]  
  35.        [HttpPost]  
  36.        [ValidateAntiForgeryToken]  
  37.        public ActionResult Create([Bind(Include = "ID,Name,LastName,Province,District,Photo,Group,RH,Location,Mobile")] User user, HttpPostedFileBase upload)  
  38.        {  
  39.            if (ModelState.IsValid)  
  40.            {  
  41.                if (upload != null && upload.ContentLength > 0)  
  42.                {  
  43.                    var avatar = new File  
  44.                    {  
  45.                        FileName = System.IO.Path.GetFileName(upload.FileName),  
  46.                        FileType = FileType.Avatar,  
  47.                        ContentType = upload.ContentType  
  48.                    };  
  49.                    using (var reader = new System.IO.BinaryReader(upload.InputStream))  
  50.                    {  
  51.                        avatar.Content = reader.ReadBytes(upload.ContentLength);  
  52.                    }  
  53.                    user.Files = new List<File> { avatar };  
  54.                }  
  55.                db.Users.Add(user);  
  56.                db.SaveChanges();  
  57.                return RedirectToAction("Index");  
  58.            }  
  59.   
  60.            return View(user);  
  61.        }  
  62.   
  63.        // GET: Users/Edit/5  
  64.        public ActionResult Edit(int? id)  
  65.        {  
  66.            if (id == null)  
  67.            {  
  68.                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  69.            }  
  70.            User user = db.Users.Find(id);  
  71.            if (user == null)  
  72.            {  
  73.                return HttpNotFound();  
  74.            }  
  75.            return View(user);  
  76.        }  
  77.   
  78.        // POST: Users/Edit/5  
  79.        [HttpPost]  
  80.        [ValidateAntiForgeryToken]  
  81.        public ActionResult Edit([Bind(Include = "ID,Name,LastName,Province,District,Photo,Group,RH,Location,Mobile")] User user)  
  82.        {  
  83.            if (ModelState.IsValid)  
  84.            {  
  85.                db.Entry(user).State = EntityState.Modified;  
  86.                db.SaveChanges();  
  87.                return RedirectToAction("Index");  
  88.            }  
  89.            return View(user);  
  90.        }  
  91.   
  92.        // GET: Users/Delete/5  
  93.        public ActionResult Delete(int? id)  
  94.        {  
  95.            if (id == null)  
  96.            {  
  97.                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  98.            }  
  99.            User user = db.Users.Find(id);  
  100.            if (user == null)  
  101.            {  
  102.                return HttpNotFound();  
  103.            }  
  104.            return View(user);  
  105.        }  
  106.   
  107.        // POST: Users/Delete/5  
  108.        [HttpPost, ActionName("Delete")]  
  109.        [ValidateAntiForgeryToken]  
  110.        public ActionResult DeleteConfirmed(int id)  
  111.        {  
  112.            User user = db.Users.Find(id);  
  113.            db.Users.Remove(user);  
  114.            db.SaveChanges();  
  115.            return RedirectToAction("Index");  
  116.        }  
  117.   
  118.        protected override void Dispose(bool disposing)  
  119.        {  
  120.            if (disposing)  
  121.            {  
  122.                db.Dispose();  
  123.            }  
  124.            base.Dispose(disposing);  
  125.        }  
  126.   
  127.    } 
That was our controlling part. It was simple, right? Now we will go to our views section.

Note: If something went wrong adding the controller, then build your solution before adding the controller. Run your project and add some users you can see the photo is unable to be added. Now open your Create.chtml located in the users subfolder of views folder. and add the following code,
  1. @model CRUDwithPic.Models.User  
  2.   
  3. @{  
  4.     ViewBag.Title = "Create A New Profile";  
  5. }  
  6.   
  7. <h2>Manage Your Profile</h2>  
  8.   
  9.   
  10. @using (Html.BeginForm("Create""Users"null, FormMethod.Post, new { enctype = "multipart/form-data" }))  
  11. {  
  12.     @Html.AntiForgeryToken()  
  13.   
  14.     <div class="form-horizontal">  
  15.   
  16.         <hr />  
  17.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  18.         <div class="form-group">  
  19.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  20.             <div class="col-md-10">  
  21.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  22.                 @Html.ValidationMessageFor(model => model.Name, ""new { @class = "text-danger" })  
  23.             </div>  
  24.         </div>  
  25.   
  26.         <div class="form-group">  
  27.             @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })  
  28.             <div class="col-md-10">  
  29.                 @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })  
  30.                 @Html.ValidationMessageFor(model => model.LastName, ""new { @class = "text-danger" })  
  31.             </div>  
  32.         </div>  
  33.   
  34.         <div class="form-group">  
  35.             @Html.LabelFor(model => model.Province, htmlAttributes: new { @class = "control-label col-md-2" })  
  36.             <div class="col-md-10">  
  37.                 @Html.EditorFor(model => model.Province, new { htmlAttributes = new { @class = "form-control" } })  
  38.                 @Html.ValidationMessageFor(model => model.Province, ""new { @class = "text-danger" })  
  39.             </div>  
  40.         </div>  
  41.   
  42.         <div class="form-group">  
  43.             @Html.LabelFor(model => model.District, htmlAttributes: new { @class = "control-label col-md-2" })  
  44.             <div class="col-md-10">  
  45.                 @Html.EditorFor(model => model.District, new { htmlAttributes = new { @class = "form-control" } })  
  46.                 @Html.ValidationMessageFor(model => model.District, ""new { @class = "text-danger" })  
  47.             </div>  
  48.         </div>  
  49.   
  50.         <div class="form-group">  
  51.             @Html.Label("Avatar"new { @class = "control-label col-md-2" })  
  52.             <div class="col-md-10">  
  53.                 <input type="file" id="Avatar" name="upload" />  
  54.             </div>  
  55.   
  56.   
  57.         </div>  
  58.   
  59.         <div class="form-group">  
  60.             @Html.LabelFor(model => model.Group, htmlAttributes: new { @class = "control-label col-md-2" })  
  61.             <div class="col-md-10">  
  62.                 @Html.EditorFor(model => model.Group, new { htmlAttributes = new { @class = "form-control" } })  
  63.                 @Html.ValidationMessageFor(model => model.Group, ""new { @class = "text-danger" })  
  64.             </div>  
  65.         </div>  
  66.   
  67.         <div class="form-group">  
  68.             @Html.LabelFor(model => model.RH, htmlAttributes: new { @class = "control-label col-md-2" })  
  69.             <div class="col-md-10">  
  70.                 @Html.EditorFor(model => model.RH, new { htmlAttributes = new { @class = "form-control" } })  
  71.                 @Html.ValidationMessageFor(model => model.RH, ""new { @class = "text-danger" })  
  72.             </div>  
  73.         </div>  
  74.   
  75.         <div class="form-group">  
  76.             @Html.LabelFor(model => model.Location, htmlAttributes: new { @class = "control-label col-md-2" })  
  77.             <div class="col-md-10">  
  78.                 @Html.EditorFor(model => model.Location, new { htmlAttributes = new { @class = "form-control" } })  
  79.                 @Html.ValidationMessageFor(model => model.Location, ""new { @class = "text-danger" })  
  80.             </div>  
  81.         </div>  
  82.   
  83.         <div class="form-group">  
  84.             @Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })  
  85.             <div class="col-md-10">  
  86.                 @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })  
  87.                 @Html.ValidationMessageFor(model => model.Mobile, ""new { @class = "text-danger" })  
  88.             </div>  
  89.         </div>  
  90.   
  91.         <div class="form-group">  
  92.             <div class="col-md-offset-2 col-md-10">  
  93.                 <input type="submit" value="Create" class="btn btn-default" />  
  94.             </div>  
  95.         </div>  
  96.     </div>  
  97. }  
  98.   
  99. <div>  
  100.     @Html.ActionLink("Back to List""Index")  
  101. </div>  
  102.   
  103. @section Scripts {  
  104.     @Scripts.Render("~/bundles/jqueryval")  

Run your application and see the result. Wow! You can add a photo now. But wait --  it does not appear on the details, what should we do? Don't worry, we will do that with two steps.

Step 1: Just replace your Details.chtml code with this one.
  1. @model CRUDwithPic.Models.User  
  2.   
  3. @{  
  4.     ViewBag.Title = "Details";  
  5. }  
  6.   
  7. <h2>Details</h2>  
  8. <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />  
  9. <div>  
  10.     <h4>User</h4>  
  11.     <hr />  
  12.     <div class="container">  
  13.           
  14.   
  15.                                     <dl class="dl-horizontal">  
  16.   
  17.                                         @if (Model.Files.Any(f => f.FileType == CRUDwithPic.Models.FileType.Avatar))  
  18.                                         {  
  19.   
  20.                                             <dt>  
  21.                                                 User Profile Picture  
  22.                                             </dt>  
  23.                                                 <dd>  
  24.                                                     <img src="~/File?id=@Model.Files.First(f => f.FileType == CRUDwithPic.Models.FileType.Avatar).FileId" alt="avatar" class="img-circle" height="100" width="100" />  
  25.                                                 </dd>  
  26.                                         }  
  27.                                         <dt>  
  28.                                             @Html.DisplayNameFor(model => model.Name)  
  29.                                         </dt>  
  30.   
  31.                                         <dd>  
  32.                                             @Html.DisplayFor(model => model.Name)  
  33.                                         </dd>  
  34.   
  35.                                         <dt>  
  36.                                             @Html.DisplayNameFor(model => model.LastName)  
  37.                                         </dt>  
  38.   
  39.                                         <dd>  
  40.                                             @Html.DisplayFor(model => model.LastName)  
  41.                                         </dd>  
  42.   
  43.                                         <dt>  
  44.                                             @Html.DisplayNameFor(model => model.Province)  
  45.                                         </dt>  
  46.   
  47.                                         <dd>  
  48.                                             @Html.DisplayFor(model => model.Province)  
  49.                                         </dd>  
  50.   
  51.                                         <dt>  
  52.                                             @Html.DisplayNameFor(model => model.District)  
  53.                                         </dt>  
  54.   
  55.                                         <dd>  
  56.                                             @Html.DisplayFor(model => model.District)  
  57.                                         </dd> 

  58.                                         <dt>  
  59.                                             @Html.DisplayNameFor(model => model.Group)  
  60.                                         </dt>  
  61.   
  62.                                         <dd>  
  63.                                             @Html.DisplayFor(model => model.Group)  
  64.                                         </dd>  
  65.   
  66.                                         <dt>  
  67.                                             @Html.DisplayNameFor(model => model.RH)  
  68.                                         </dt>  
  69.   
  70.                                         <dd>  
  71.                                             @Html.DisplayFor(model => model.RH)  
  72.                                         </dd>  
  73.   
  74.                                         <dt>  
  75.                                             @Html.DisplayNameFor(model => model.Location)  
  76.                                         </dt>  
  77.   
  78.                                         <dd>  
  79.                                             @Html.DisplayFor(model => model.Location)  
  80.                                         </dd>  
  81.   
  82.                                         <dt>  
  83.                                             @Html.DisplayNameFor(model => model.Mobile)  
  84.                                         </dt>  
  85.   
  86.                                         <dd>  
  87.                                             @Html.DisplayFor(model => model.Mobile)  
  88.                                         </dd>  
  89.   
  90.                                     </dl>  
  91.                                 </div>  
  92.                             </div>   
  93. <br />  
  94. <p>  
  95.     @Html.ActionLink("Edit""Edit"new { id = Model.ID }) |  
  96.     @Html.ActionLink("Back to List""Index")  
  97. </p> 
Step 2: Add a file controller!!! (We need to add an empty controller to the controllers folders and name it FileController) Here is the code. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using CRUDwithPic.Models;  
  7.   
  8. namespace CRUDwithPic.Controllers  
  9. {  
  10.     public class FileController : Controller  
  11.     {  
  12.         private UserDBContext db = new UserDBContext();  
  13.         //  
  14.         // GET: /File/  
  15.         public ActionResult Index(int id)  
  16.         {  
  17.             var fileToRetrieve = db.Files.Find(id);  
  18.             return File(fileToRetrieve.Content, fileToRetrieve.ContentType);  
  19.         }  
  20.     }  

Note: If something went wrong then add this piece of code to the views web.config file, otherwise enjoy your application.
  1. <add namespace="CRUDwithPic.Models" /> 
Test the result now. Hope that helped you. Stay tuned for the next Article (Customizing Details view and searching) . Don't hesitate to ask questions in the comments.