Using MVC3, Razor Helpers, and jCrop to upload and crop images.

UPDATE – Original Source Link

I somehow miraculously stumbled upon the source code for this project, so I’m including a link to it here:

JCropExample

Note: If you get a “Project Type Not Supported” in Visual Studio 2010, you need to download the MVC 3 Tools Update  (or install SP1, I believe).

The link is here: http://www.microsoft.com/en-us/download/details.aspx?id=1491

Overview

A common requirement for websites that allow user registration is the uploading of user profile images.  In many cases, this can be a bother for both user and developer.  The implementation of image cropping functionality has traditionally been somewhat cumbersome for developers, and users are generally pained by having to crop an image offline before uploading it, especially more inexperienced computer users.

We’ll explore how to quickly and easily create a solution using ASP.NET MVC3 and 2 of the new Razor helpers, the FileUpload and WebImage helpers and jCrop, an excellent jQuery plugin for image cropping.

Downloading/Installing Jcrop

Jcrop is available for download from the following link: Jcrop Webpage

Just drop your CSS and the Jcrop.gif file in your Content foler, and include the jQuery.jCrop.min.js in your Scripts folder.

FileUpload and WebImage for uploading images

Adding the Microsoft.Web.Helpers Library

To add the Microsoft.Web.Helpers library, install NuGet, and install the Microsoft.Web.Helpers package.  Also, include the System.Web.Helpers package included with ASP.NET MVC 3.

We’re creating a very simple solution for displaying and cropping images here.

First, we’ll need a view model for our profile editing view.

Code Snippet
  1. public class ProfileViewModel
  2. {
  3. [UIHint("ProfileImage")]
  4. public string ImageUrl { get; set; }
  5. }

You can see we’re using a UIHint to simplify the naming of our Display and Editor templates.

Next, we’ll create an editor template for our image:

Code Snippet
  1. @model System.String
  2. <img src="@(String.IsNullOrEmpty(Model) ? "" : Model)" id="profileImage" />

Now, lets create our index page.

Code Snippet
  1. @model WebHelpers.Models.WebImage.ProfileViewModel
  2. @using Microsoft.Web.Helpers;
  3. @{
  4. ViewBag.Title = "Index";
  5. }
  6. <h2>Index</h2>
  7. @using (Html.BeginForm("Upload", "WebImage", FormMethod.Post, new { @encType = "multipart/form-data" }))
  8. {
  9. @Html.DisplayFor(x => x.ImageUrl)<br/>
  10. <input type="submit" name="submit" text="upload" />
  11. }

We’ve got a basic HTML form here that will post to the Upload action method with the encoding type set to multipart/form-data for file upload.  We’ll need to add in the code for the upload box.  For this, we’ll use the FileUpload helper.

The FileUpload helper

Code Snippet
  1. @FileUpload.GetHtml(initialNumberOfFiles:1, allowMoreFilesToBeAdded: true, includeFormTag: false, addText: "Add Files", uploadText: "Upload File")<br />

The FileUpload helper gives developers an extremely quick and flexible way to add multiple file upload support to a form, using javascript to handle adding multiple file upload controls.  The GetHtml method is used to render a file upload control using the optional parameters shown above.  The snippet above results in the upload control displayed below.

image

Code Snippet
  1. public ActionResult Upload(ProfileViewModel model)
  2. {
  3. var image = WebImage.GetImageFromRequest();
  4. if (image != null)
  5. {
  6. if (image.Width > 500)
  7. {
  8. image.Resize(500, ((500 * image.Height) / image.Width));
  9. }
  10. var filename = Path.GetFileName(image.FileName);
  11. image.Save(Path.Combine("../TempImages", filename));
  12. filename = Path.Combine("~/TempImages", filename);
  13. model.ImageUrl = Url.Content(filename);
  14. }
  15. return View("Index", model);
  16. }

For our purposes, we’ll use the following FileUpload command for a single file upload:

Code Snippet
  1. @FileUpload.GetHtml(initialNumberOfFiles: 1, includeFormTag: false, uploadText: "Upload File")<br />

Receiving Uploaded Files

To receive and save the uploaded file, we’ll implement the Upload action method using the WebImage helper to save the file:

Code Snippet
  1. public ActionResult Upload(ProfileViewModel model)
  2. {
  3. var image = WebImage.GetImageFromRequest();
  4. if (image != null)
  5. {
  6. if (image.Width > 500)
  7. {
  8. image.Resize(500, ((500 * image.Height) / image.Width));
  9. }
  10. var filename = Path.GetFileName(image.FileName);
  11. image.Save(Path.Combine("../TempImages", filename));
  12. filename = Path.Combine("~/TempImages", filename);
  13. model.ImageUrl = Url.Content(filename);
  14. }
  15. return View("Index", model);
  16. }

Using the GetImageFromRequest static method on the WebImage class, we retrieve a WebImage object representing the uploaded file.  Since we’re constraining all images to a maximum of 500 pixels in width, we’ll use the Width property to check the size, and use the Resize functionality of the WebImage helper to resize the image in memory. We the get the filename and use the Save function of the WebImage helper to svae the file to a TempImages folder. We then retrieve the image url and set it back to the ImageUrl property of our ProfileViewModel instance and return the model to our view.   This results in the following:

image

In our app, we’re displaing a profile picture constrained to a 1 to 1 aspect ratio.  this causes most images we’d upload to appear tiny and squished.  This results in an ugly profile picture.  Lets fix this problem by giving our users the ability to crop their image using jCrop.

Cropping using jCrop and WebImage

jCrop requires a few image properties initially to set the initial crop window.  We’ll create an Editor input model that will give us the ability to both supply those values, and to retrieve the final cropping dimensions to perform the cropping action.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. namespace WebHelpers.Models.WebImage
  6. {
  7. public class EditorInputModel
  8. {
  9. public ProfileViewModel Profile { get; set; }
  10. public double Top { get; set; }
  11. public double Bottom { get; set; }
  12. public double Left { get; set; }
  13. public double Right { get; set; }
  14. public double Width { get; set; }
  15. public double Height { get; set; }
  16. }
  17. }

Out EditorInputModel contains our original ProfileViewModel which supplies our ImageUrl property, but may contain other profile information for the solution you’re implementing.  It also contains both size and position properties for the crop selection.  We’re going to set these properties to set the initial cropping indicator.

Updating our Upload action method:

Paste the following code at Line 17 in our Upload action method above:

Code Snippet
  1. var editModel = new EditorInputModel()
  2. {
  3. Profile = model,
  4. Width = image.Width,
  5. Height = image.Height,
  6. Top = image.Height * 0.1,
  7. Left = image.Width * 0.9,
  8. Right = image.Width * 0.9,
  9. Bottom = image.Height * 0.9
  10. };
  11. return View("Editor", editModel);

This code populates our EditorInputModel with the initial information we need to supply jCrop with to do the cropping operation.  We’re passing this information then to the “Editor” view.

The editor view

First, we’re going to use jCrop to allow us to crop our image with a live thumbnail preview.  To do that, we need to display our image twice.  We’ll use the following editor template:

Code Snippet
  1. @model System.String
  2. <div id="cropContainer">
  3. <div id="cropPreview">
  4. <img src="@(String.IsNullOrEmpty(Model) ? "" : Model)" id="preview" />
  5. </div>
  6. <div id="cropDisplay">
  7. <img src="@(String.IsNullOrEmpty(Model) ? "" : Model)" id="profileImageEditor" />
  8. </div>
  9. </div>

This simple editor template creates 2 img tags displaying the image, one named “preview”and one named “profileImageEditor”.  The size of preview is constrained to a 1 to 1 aspect ratio using CSS.

Next, we’ll need our Editor view.

Code Snippet
  1. @model WebHelpers.Models.WebImage.EditorInputModel
  2. @{
  3. ViewBag.Title = "Editor";
  4. }
  5. @section HeaderSection
  6. {
  7. <link href="@Url.Content("~/Content/jquery.Jcrop.css")" rel="stylesheet" type="text/css" />
  8. <script src="@Url.Content("~/Scripts/jquery.Jcrop.js")" type="text/javascript"></script>
  9. }
  10. <h2>Editor</h2>
  11. <div id="mainform">
  12. @using(Html.BeginForm("Edit","WebImage", FormMethod.Post))
  13. {
  14. @Html.EditorFor(x=>x.Profile.ImageUrl)
  15. @Html.HiddenFor(x=>x.Left)
  16. @Html.HiddenFor(x=>x.Right)
  17. @Html.HiddenFor(x=>x.Top)
  18. @Html.HiddenFor(x=>x.Bottom)
  19. @Html.HiddenFor(x => x.Profile.ImageUrl)
  20. <input type=’submit’ name=’action’ value=’Crop’ />
  21. }
  22. </div>

First, we’re referencing our jCrop css and javascript files, alogn with creating the form for passing back our cropped image values.

We display our editor for the image, and create hidden HTML fields for the Left, Right, Top, and Bottom properties of the cropping indicator.  These we pass back to perform the cropping operation.

Next, we’ll need to add some javascript in a script tag at the bottom of this view:

Code Snippet
  1. $(function () {
  2. jQuery(‘#profileImageEditor’).Jcrop({
  3. onChange: showPreview,
  4. onSelect: showPreview,
  5. setSelect: [@Model.Top, @Model.Left, @Model.Right, @Model.Bottom],
  6. aspectRatio: 1
  7. });
  8. });
  9. function showPreview(coords)
  10. {
  11. if (parseInt(coords.w) > 0)
  12. {
  13. $(‘#Top’).val(coords.y);
  14. $(‘#Left’).val(coords.x);
  15. $(‘#Bottom’).val(coords.y2);
  16. $(‘#Right’).val(coords.x2);
  17. var width = @Model.Width;
  18. var height = @Model.Height;
  19. var rx = 100 / coords.w;
  20. var ry = 100 / coords.h;
  21. jQuery(‘#preview’).css({
  22. width: Math.round(rx * width) + ‘px’,
  23. height: Math.round(ry * height) + ‘px’,
  24. marginLeft: ‘-’ + Math.round(rx * coords.x) + ‘px’,
  25. marginTop: ‘-’ + Math.round(ry * coords.y) + ‘px’
  26. });
  27. }
  28. }

here we’re calling .Jcrop on our profileImageEditor image tag, setting the jCrop onChange and onSelect callsback to the showPreview function.  We’re also setting the Model.Top, model.left, Model.Right, and Model.Bottom properties to the html form values being automatically set by jCrop.  We’re also constraining the selector to an aspect ratio of 1.

In the showPreview function, we’re grabbing the crop selectors values and updating our thumbnail window to show a preview of the cropping operation.

Now, after launching our app and submitting an image for upload, we’re given the following view:

image

On the left, we have our main image display with our jCrop cropping tool, and our live thumbail perview to the left, along with the “Crop” button to submit our post request.

The last thing we need to do is to implement our Edit action method, which will do the actual cropping using the WebImage helper.

The edit action method

Code Snippet
  1. public ActionResult Edit(EditorInputModel editor)
  2. {
  3. var image = new WebImage("~" + editor.Profile.ImageUrl);
  4. var height = image.Height;
  5. var width = image.Width;
  6. image.Crop((int)editor.Top, (int)editor.Left, (int)(height – editor.Bottom), (int)(width – editor.Right));
  7. var originalFile = editor.Profile.ImageUrl;
  8. editor.Profile.ImageUrl = Url.Content("~/ProfileImages/" + Path.GetFileName(image.FileName));
  9. image.Resize(100, 100, true, false);
  10. image.Save(@"~" + editor.Profile.ImageUrl);
  11. System.IO.File.Delete(Server.MapPath(originalFile));
  12. return View("Index", editor.Profile);
  13. }

First, we load the original image form disk using the ImageUrl we had stored in our ProfileViewModel instance. We retrieve the width and eight from the loaded image, as these are our initial width and height values we’ll need to perform our cropping.

We then call the Crop method of the WebImage instance, supplying the top and left values on the original image where the crop begins, and calculating the width and height of the resulting image by subtracting the bottom of the crop tool from the height of the image, and the rigth of the crop tool from the width of the original image.

We then grab the original source image URL before setting the ImageURL property to the new location we’ll be saving our cropped image.  Now that we’ve cropped our image to a 1 to 1 aspect ratio, we’ll resize to the final profile image size, 100 x 100.  We then save the image to our new ImageURL, delete the original source image, and pass the cropped image back to the index page.

After our cropping operation, we’re returned to our index view with our new cropped image.

image

This entry was posted in 0-Uncategorized. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

37 Comments

  1. David
    Posted February 10, 2011 at 8:38 pm | Permalink

    It would help if you include file path + names above the snippets. Thanks. Nice post.

  2. Mark
    Posted March 28, 2011 at 12:00 am | Permalink

    I agree…file path + names would be very helpful. The post is great, except I don’t know where anything should go. It’s useful never-the-less though. Thank you.

  3. Ed
    Posted April 3, 2011 at 12:41 pm | Permalink

    This is a very good article – it would be useful if the source code was available as it is difficult to understand where things go

  4. LEO
    Posted April 13, 2011 at 1:27 pm | Permalink

    can you give me this(Using MVC3, Razor Helpers, and jCrop to upload and crop images.) source code,thank you

  5. Michael Gerety
    Posted April 13, 2011 at 1:30 pm | Permalink

    To be honest, I don’t think I have the source code for this any more. I was very careful to be sure to include all the relevant source to accomplish this. Is there something specific that you’re having trouble with?

  6. Michael Gerety
    Posted April 13, 2011 at 1:31 pm | Permalink

    Good point. I’ll be sure to do that next time.

  7. James Jiang
    Posted May 3, 2011 at 4:27 am | Permalink

    May I have you this(Using MVC3, Razor Helpers, and jCrop to upload and crop images.) source code,thank you!
    Just for learing.

  8. James
    Posted May 3, 2011 at 7:02 am | Permalink

    Can you give me this code source to learn? Thank you!

  9. carlo
    Posted June 3, 2011 at 8:00 pm | Permalink

    Hi,
    Great article! bear with me but for the first part where you add @model System.String and the image tag – that’s a separate partial view right? so we have index view and another partial view containing the img tag?

    Thanks,
    Carlo

  10. Thomas
    Posted July 27, 2011 at 10:31 pm | Permalink

    I have the same problem as “carlo”…

    You create a editor template and then an editor view…

    but where do you use the editor template?

    Thanks,
    Thomas

  11. Thomas
    Posted July 27, 2011 at 11:13 pm | Permalink

    Ok. your tutorial requires some insight into editorfor and display for template setup…

    I got it to work after i made 2 folders inside the shared folder… named “EditorTemplates” and “DisplayTemplates” and the created a file named ProfileImage.cshtml where i pasted your code for the corresponding file.

    Your tutorial is the best i found by googling, and im sure im not the only one thats not familiar with those template folder.

  12. Thomas
    Posted July 28, 2011 at 5:09 pm | Permalink

    I just want to add for people that to replicate the result of the tutorial i added these lines to the css.

    #cropPreview
    {
    float : left;
    overflow : hidden;
    width : 100px;
    height : 100px;
    }

    #cropDisplay
    {
    float : left;
    clear : right ;
    }

    Now my picture upload works beautifully…
    Thanks again for this great tutorial!

  13. Posted August 2, 2011 at 6:02 pm | Permalink

    When setting up an MVC 3 application, the foreign keys that should allow drop down lists to select an item do not get rendered as drop downs, but as static inputs. This can be resolved by creating a custom display and view for that field.
    We will need to start by creating a custom partial view that will live in “~/Views/Shared/DisplayTemplates/UserGuid.cshtml”, and “~/Views/Shared/EditTemplates/UserGuid.cshtml”. The code for one is located below:
    @model Guid

    @{
    incMvcSite.Models.MvcSiteDB db = new incMvcSite.Models.MvcSiteDB();
    incMvcSite.Models.SecUser usr = db.SecUsers.Single(u => u.Guid == Model);
    }
    @usr.Display

    This is a display for template that will look up the item in the referenced table and display it. We also need an edit for template as follows:
    @model Guid
    @{
    incMvcSite.Models.MvcSiteDB db = new incMvcSite.Models.MvcSiteDB();
    SelectList items = new SelectList(db.SecUsers.OrderBy(i => i.Display).ToList(), “Guid”, “Display”, Model);
    }
    @Html.DropDownList(“”, items)

    The edit for template is implemented as a drop down list. Originally, we has used static HTML code, but the problem will appear of implementing a “prefix”. Static HTML code does get handled by HTML helpers, so it’s recommended that you use the HTML.DropDownList().
    To force the MVC framework to use the new Display and Edit for templates, we need to annote our model item an add the following line:
    [UIHint("UserGuid")]

    This will cause MVC to use the Display and Edit templates named “UserGuid”, which are just partial views.

  14. Kylie
    Posted August 18, 2011 at 3:49 pm | Permalink

    Thanks for this. However the source code would have been really helpful as it would have given me a better idea of what went where. I struggled a bit but this is still the best tutorial in this genre!

  15. Posted August 24, 2011 at 3:07 am | Permalink

    Thanks for the great tut! I have a question though; Is there a way to link this up to a json or ajax request? I currently working on a content editor and I need the ability to upload images while keeping the content on the page until I save or publish it. Any ideas?

    Regards,

    Ron Del Rosario

  16. Sen K. Mathew
    Posted August 24, 2011 at 5:25 am | Permalink

    Sir
    I went through your code and re-created it. But i am getting only the image url instead of image.
    I created the profileImage.cshtml under Editor Template.
    But some thing is keeping it from displaying image.
    more over

    @model WebHelpers.Models.WebImage.ProfileViewModel in index page
    what is Webhelpers and WebImages(is it Directory?). I have added reference but not getting it in index page.

    It would be very helpfull if you could provide us with a source code

    Thanks in advance
    Sen

  17. Sen K. Mathew
    Posted August 24, 2011 at 7:05 am | Permalink

    Hi All
    Using MVC3, Razor Helpers, and jCrop to upload and crop images.
    By Michael Gerety article was wonderfull.
    But there were confusion here and there at first. But I could come up with a working code. I am not discussing the JCrop Part here.

    Hope my explanation would be helpfull to those who are not so familiar with MVC3 Razor. I am also a Beginner like some of you and struggled a little to make it work.
    Here is the explanation
    1. Creat a Project under MVC3 Razor. Mine is Store
    2. Under Models Folder Creat a File Named ProfileViewModel.cs
    ProfileViewModel.cs contains following codes
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;

    namespace Store.Models
    {
    public class ProfileViewModel
    {
    [UIHint("profileImage")]
    public string ImageUrl {
    get;
    set;
    }
    }
    }

    here the namespace will be a different one for you(namespace Store.Models at top).

    Next you create a folder under View\Shared
    Folder name must be DisplayTemplates. Please do not change the name of the folder. why? Because here we are using
    @Html.DisplayFor(x => x.ImageUrl) in the indext page. It will look in the DisplayTemplates folder for the UIHint File.

    So your folder will now look
    View\Shared\ DisplayTemplates
    under the folder DisplayTemplates(View\Shared\ DisplayTemplates)
    Create a view (Empty view) profileImage.cshtml
    for this Click on the DisplayTemplates and choose option Add > View
    ie
    View Name : profileImage.cshtml
    View engine :Razor(cshtml)
    then tick the checkbox ‘”Use a layout or masterpage”
    Click Add.

    Now add following code in profileImage.cshtml under DisplayTemplates
    @model System.String
    @Html.Raw(” “)
    Please note that the id ‘profileImage’ . This name must be same as the one you declared in UIHint in Model ProfileViewModel.cs
    [UIHint("profileImage")]

    Now Create a Controller named
    ProfileViewController.cs under Controller Folder.
    copy the code below to ProfileViewController.cs

    public ActionResult Index()
    {
    ProfileViewModel objPVM = new ProfileViewModel();
    return View(objPVM);
    }

    [HttpPost]
    public ActionResult Upload(ProfileViewModel model)
    {
    ProfileViewModel objPVM = new ProfileViewModel();

    var image = WebImage.GetImageFromRequest();

    if (image != null)
    {
    if (image.Width > 500)
    {
    image.Resize(500, ((500 * image.Height) / image.Width));
    }

    var filename = Path.GetFileName(image.FileName);
    var imageUploadPath = Path.Combine(Server.MapPath(“/Uploads/Images”), filename);
    //image.Save(Path.Combine(“/Uploads/Images”, filename));
    image.Save(imageUploadPath);

    model.ImageUrl = Url.Content(Path.Combine(“/Uploads/Images”, filename));
    }

    return View(“Index”, model);
    //return View(objPVM);
    }

    you must have following references at the top of ProfileViewController.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Routing;
    using System.Web.Mvc;
    using System.Web.Helpers;
    using System.IO;

    using Store.Models;

    here replace ’store’ with your namespace.
    Ok
    Now We have
    1. Model ->ProfileViewModel.cs
    2. Controller -> ProfileViewController.cs
    3. a DisplayTemplates -. profileImage.cshtml

    Now we need to create and empty Index page
    for this
    You can do it in many ways
    1. Just Right click on Index in ProfileViewController.cs Controller
    public ActionResult Index()
    {
    ProfileViewModel objPVM = new ProfileViewModel();
    return View(objPVM); —————————–> RightClick
    }
    And Choose AddView File name is Index.cshtml
    Select Empty View and Click Add button

    Copy the code below to Index.cshtml
    @model Store.Models.ProfileViewModel
    @using Microsoft.Web.Helpers
    @{
    ViewBag.Title = “Index”;
    }

    Index
    @using (Html.BeginForm(“Upload”, “ProfileView”, FormMethod.Post, new { @encType = “multipart/form-data” }))
    {
    @Html.DisplayFor(x => x.ImageUrl)

    @FileUpload.GetHtml(initialNumberOfFiles:1, allowMoreFilesToBeAdded: true, includeFormTag: false, addText: “Add Files”, uploadText: “Upload File”)

    }
    Please note Replace ’store’ at top with your namespace.
    If you have selected same file names then you only have to change the namespace if it is different.
    One more thing you must create a file upload folder in your porject
    Mine is Uploads/Images
    Your Directory structure will be
    Store
    |_ Controllers\ProfileViewController.cs
    |_Models\ProfileViewModel.cs
    |_Uploads
    |_Images
    |_Views
    |_ProfileView\Index.cshtml
    |_Shared
    |_DisplayTemplates\profileImage.cshtml
    Ok Now Combile it and run it.

    Hope this will help you.

  18. Posted August 26, 2011 at 1:33 pm | Permalink

    This is pretty good stuff, thanks for sharing! This will help me hit the ground running on some views I need.

  19. Bjørn Ove Thue
    Posted September 9, 2011 at 8:26 am | Permalink

    Sen K. Mathew: You really cleared things up. Thanks a lot!

  20. Neal Helman
    Posted November 27, 2011 at 3:48 pm | Permalink

    Thanks for putting this out there in the cloud, Michael.

    Sen K. Mathew’s comment really put it together for me. I have successfully incorporated the fileupload helper into my project.

    I have one question, though. The HTML generated by the fileupload helper is all in DIVs, which doesn’t really work with overall display of the page in which I’m using the helper. How can I get the fileupload helper to display in SPANs rather than DIVs – inline rather than block. I get the feeling I’m going to have to modify the source if I could get ahold of it. Other than the display issue, it’s a nifty tool!

  21. Posted December 5, 2011 at 12:01 pm | Permalink

    Hi,

    First of all I would like to thank you for this wonderful walkthrough.
    It is working without a problem but I moved forward and use it in a registration form. The problem starts from that point.

    Problem is:

    I have a control named Registration and also a view named Registration.

    I put the view code into it and created only a Editor form.
    Picture part is working without any problem but when I try to finish filling the form and push submit.

    The page (after editing picture) keeps in Editor so submit function is calling the Editor once more and you may guess the rest.

    CONTROLS ARE:

    public ActionResult Registration(ProfileView model, string nextButton, string uploadButton)
    {
    if (uploadButton != null)
    {

    var image = WebImage.GetImageFromRequest();

    if (image != null)
    {
    if (image.Width > 500)
    {
    image.Resize(500, ((500 * image.Height) / image.Width));
    }

    var filename = Guid.NewGuid().ToString() + Path.GetFileName(image.FileName);
    image.Save(Path.Combine(“../TempImages”, filename));
    filename = Path.Combine(“~/TempImages”, filename);
    ProfilePicture profPic = new ProfilePicture();
    profPic.ProfilePictureUrl = Url.Content(filename);
    model.profilePicture = profPic;

    var editModel = new EditorInputModel()
    {
    ProfilePicture = model.profilePicture,
    Width = image.Width,
    Height = image.Height,

    Top = image.Height * 0.1,
    Left = image.Width * 0.9,
    Right = image.Width * 0.9,
    Bottom = image.Height * 0.9
    };
    return View (“Editor”, editModel);
    }

    return View(“ExtraDetails”, model);
    }

    if (nextButton != null && ModelState.IsValid)
    {
    //SAVE STUFF HERE
    return RedirectToAction(“OtherDetails”);
    }
    else
    return View(model);
    }

    public ActionResult Edit(EditorInputModel editor)
    {
    var image = new WebImage(“~” + editor.ProfilePicture.ProfilePictureUrl);
    var height = image.Height;
    var width = image.Width;

    image.Crop((int)editor.Top, (int)editor.Left, (int)height – (int)editor.Bottom, (int)width – (int)editor.Right);
    var originalFile = editor.ProfilePicture.ProfilePictureUrl;
    //editor.ProfilePicture.ProfilePictureUrl = Url.Content(“~/ProfileImages/” + user.UserId.ToString() + “/” + Path.GetFileName(image.FileName));
    editor.ProfilePicture.ProfilePictureUrl = Url.Content(“~/ProfileImages/” + Path.GetFileName(image.FileName));
    image.Resize(150, 150, true, false);
    image.Save(@”~” + editor.ProfilePicture.ProfilePictureUrl);
    System.IO.DirectoryInfo picturesFolder = new DirectoryInfo(Server.MapPath(“~/TempImages”));
    foreach (FileInfo file in picturesFolder.GetFiles())
    {
    file.Delete();
    }
    //System.IO.File.Delete(Server.MapPath(originalFile));
    ProfileView model = new ProfileView();
    model.profilePicture = editor.ProfilePicture;
    if (Request.IsAjaxRequest())
    return PartialView(“Registration”, model);
    return View(“Registration”, model);
    }

    VIEWS ARE:

    REG:

    @model User.Models.ProfileView
    @using Microsoft.Web.Helpers;
    @{
    ViewBag.Title = “Details”;
    }

    @using (Html.BeginForm((string)ViewBag.FormAction, “Registration”, FormMethod.Post, new { @encType = “multipart/form-data” }))
    {
    @Html.ValidationSummary(true)
    …………………….

    EDITOR:

    @model User.Models.EditorInputModel
    @{
    ViewBag.Title = “Editor”;
    }

    @using (Html.BeginForm(“Edit”, “Registration”, FormMethod.Post))
    {

    Any help appreciated. Thanks!

  22. mvc_beginner
    Posted December 14, 2011 at 12:04 am | Permalink

    Hi, has anyone had successful in get this to work. I followed Sen K. Mathew’s post exactly but I cannot get it to work. After I browse and select the image, the Upload function in my controller is not executed. I had to submit to get the Upload function to be executed. Is this how it’s suppose to work? – I believe it should upload straight after the file is selected.
    Pls help me get the sample working….

    Thanks

  23. David Kennedy
    Posted December 20, 2011 at 7:00 pm | Permalink

    @mvc_beginner, that is how it’s supposed to work.

    Thanks, Michael, for the post. And especially to Ser for clearing everything up :)

  24. David Kennedy
    Posted December 20, 2011 at 8:18 pm | Permalink

    I should also point out that if you want single file upload instead of multiple, leave the “allowMoreFilesToBeAdded” parameter in the FileUpload.GetHtml() helper function call, but set it to false.

  25. Brian Grant
    Posted April 26, 2012 at 3:52 pm | Permalink

    This is the only article Ive found googling. Its to bad you didnt explain where any of the code actualy goes (snipit) isnt very helpful. With any luck I’ll find another posting on this subject that can shead some more light on this.

  26. tiago
    Posted July 9, 2012 at 6:41 pm | Permalink

    Please, provide the design for download for the article to be perfect.

  27. Paulo Rogério
    Posted August 8, 2012 at 8:19 pm | Permalink

    Poderia manda o exemplo para meu email paulorogerio.analista@gmail.com?

    send me for email

  28. Jack
    Posted October 6, 2012 at 10:48 pm | Permalink

    Thank you for the tutorial. I needed the image upload. But cant wait to do the filecropper as well.

  29. iii
    Posted January 3, 2013 at 11:07 pm | Permalink

    HOW TO USE THIS CODE WHERE I CAN WRITE THIS CODE

    @model System.String

  30. CAN YOU PLEASE SEND
    Posted February 27, 2013 at 7:21 am | Permalink

    PLEASE SEND ME THE SOURCE CODE TO LOHITH.BANA@YAHOO.COM

  31. Naga
    Posted March 22, 2013 at 12:57 pm | Permalink

    I read thru each every line, sounds very promising. An example working code could could have made it even more promising than this. However thanks for sharing such genius work.

  32. tiagomx
    Posted May 14, 2013 at 10:00 am | Permalink

    hello i am new to mvc you could send the sorce of this example so that I can better understand’m developing a web application for registration of employees and’m having serious difficulties in add and display the picture of the staff … great post thank you

  33. Posted May 14, 2013 at 11:23 am | Permalink

    I somehow over 2 years later stumbled across the source for this post as I was browsing an old drive backup I had.

    I’ve tested this out and it works. I hope it can help some of you!

  34. anil
    Posted July 12, 2013 at 3:03 am | Permalink

    Table:

    public int ActorID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Price { get; set; }
    [DataType(DataType.ImageUrl)]
    public string Image { get; set; }

    My Controller code:

    public ActionResult Details(int id)
    {
    Actor ac = db.Actors.Single(x => x.ActorID == id);
    return View(ac);

    View:

    @model MvcApplication1.Models.Actor

    @{
    ViewBag.Title = “Details”;
    }

    Details

    Actor

    @Html.DisplayNameFor(model => model.Name)

    @Html.DisplayFor(model => model.Name)

    @Html.DisplayNameFor(model => model.Description)

    @Html.DisplayFor(model => model.Description)

    @Html.DisplayNameFor(model => model.Price)

    @Html.DisplayFor(model => model.Price)

    @Html.DisplayNameFor(model => model.Image)

    @*@Html.DisplayFor(model => model.Image)*@

    @Html.ActionLink(“Edit”, “Edit”, new { id=Model.ActorID }) |
    @Html.ActionLink(“Back to List”, “Index”)

    This is my code At the time of clicking Details option It will display data correctly But ,Along with IMAGE not displaying,

    please Correct my above code

  35. Posted September 23, 2013 at 11:54 am | Permalink

    can you share code for me , thanks so much
    email : nguyenthuonguit@gmail.com

  36. Posted November 7, 2013 at 8:11 am | Permalink

    Here is a link to working source code for this blog, I noticed it had some things missing and it took me a long time to fix it xD.

    Just run it and you will get a working example.
    https://mega.co.nz/#!Zx5U3JzZ!XZCZCCiuXdlAtt6j2X_0VT4zXFVIPyvuECrZXeCFLwo

  37. Posted November 9, 2013 at 5:51 am | Permalink

    Working project on github: https://github.com/Krotar/MVC-4-Cropper

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*