1

i am using asp.net MVC3

I want to upload the image before form is submit.

below is my code

 <div>
   @using (Html.BeginForm("SaveData", "Home", FormMethod.Post, new { @enctype =      "multipart/form-data" }))
   {
     <div> Image: 
           <input type="file" name="uploadFile" onchange="upload(this);" /></div>
     <div> Name: 
           @Html.TextBoxFor(model => model.Name)</div>
     <div> Address:  
           @Html.TextBoxFor(model => model.Address)</div>
     <div> Phone: 
           @Html.TextBoxFor(model => model.Phone)</div>

     <input type="submit" name="save" id="savedata" title="save" 
        value="save"  />
}         
</div>

<script type="text/javascript">
   function UploadFile(image) {
        //call controller action UploadFile
         $.ajax({
            type: "Post",
            url: "Home/UploadFile",
            data: image,       //This is wrong
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        });
   }
</script>

Now on Controller side

 public ActionResult UploadFile(HttpPostedFileBase uploadFile)
 {
     //save image
 }

can any one can suggest how can i upload the image before posting my form to save data.

BrainCoder
  • 5,197
  • 5
  • 30
  • 33

1 Answers1

1

$.ajax() is not capable of that. There are jQuery plugins available though, that do this for you. Here's one. This thread also discusses loads of options to do this. Do note that file upload through AJAX is a relatively new feature and not all browsers support it.

Community
  • 1
  • 1
J.P.
  • 5,567
  • 3
  • 25
  • 39