2

I am new to razor view engine. I am stuck with a situation where I want to upload an Image with Change event of image browser. Jquery function is given below:

$("#billUpload").change(function (){
$('#uploadImageForm').submit();
}

Razor view code is given below:

 @using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "uploadImageForm" }))            
        {
            <span class="file-input btn btn-sm btn-default btn-file">
                Browse&hellip;
                <input id="billUpload" name="File" type="file">
            </span>
        }

Controller's code is here:

[HttpPost]
    public ActionResult Upload(HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {
            if (file == null)
            {
                ModelState.AddModelError("File", "Please Upload Your file");
            }
            else if (file.ContentLength > 0)
            {
                int MaxContentLength = 1024 * 1024 * 4; //Size = 4 MB
                string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
                if (!AllowedFileExtensions.Contains
     (file.FileName.Substring(file.FileName.LastIndexOf('.'))))
                {
                    ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
                }
                else if (file.ContentLength > MaxContentLength)
                {
                    ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
                }
                else
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Content/images/Bill/"), fileName);
                    file.SaveAs(path);
                    ModelState.Clear();
                    ViewBag.Message = "File uploaded successfully. File path :   ~/Content/image/Bill/" + fileName;
                }
            }
        }
        return Json("Done",JsonRequestBehavior.AllowGet);
    }

Now this entire code runs with no problem for uploading image but I fail to understand how to display this json message return by controller in alert box. Thanks in advance.

Sid M
  • 4,268
  • 4
  • 27
  • 47
RaviKant Hudda
  • 1,012
  • 10
  • 22
  • 1
    You should submit form with `ajax` to do that. – Ibrahim Khan Dec 02 '15 at 08:04
  • In this case controller gets HttpPostedFileBase null. That I have tried. – RaviKant Hudda Dec 02 '15 at 08:07
  • What alert box are you referring to? You doing a normal submit so its just going to redirect to a new page (and display "Done" because you returning a `JsonResult`) –  Dec 02 '15 at 08:07
  • @StephenMuecke I want the result to be produce on the same page. – RaviKant Hudda Dec 02 '15 at 08:09
  • Then use ajax with `FormData` (refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681)). But then what is the point of adding `ViewBag` properties and `ModelState` errors which will never be used? –  Dec 02 '15 at 08:10

1 Answers1

4

You can do it like following using ajax. Hope this helps.

$("#billUpload").on('change', (function(e) {
    e.preventDefault;
    var formData = new FormData($('#uploadImageForm')[0]);

    $.ajax({
        url : "/Home/Upload",
        type : "POST", 
        data : formData,
        cache : false,
        contentType : false,
        processType : false,
        success : function(data) {
            alert(data);
        }
    });
}));
Ibrahim Khan
  • 19,912
  • 7
  • 35
  • 51