-1

I'm trying to insert data with image to database. The data is stored to database, all things are fine but when i try to do the same thing using ajax, the ajax call is unable to call the controller action Method. here is my code.

This is my Form in View

  <form id="InsertForm" name="InsertForm"  enctype="multipart/form-data">
        <div class="form-group">
              <label for="Name">Name</label>
              <input type="text" class="form-control" name="StudentName" id="name"/>
        </div>
        <div class="form-group">
              <label for="LastName">Last Name</label>
              <input type="text" class="form-control" name="StudentLastName" id="last" />
        </div>
        <div class="form-group">
              <label for="Address">Address</label>
              <input type="text" class="form-control" name="StudentAddress" id="address"/>
        </div>
        <div class="form-group">
              <label for="Gender">Gender</label>
              <input type="text" class="form-control" name="Gender"  id="gender"/>
        </div>
        <div class="form-group">
              <label for="Image">Image</label>
               <input type="file" class="form-control" id="StudentImage" name="StudentImage" />
        </div>

        <button id="saveclick" type="submit" name="save">Save</button>

  </form>

This is my Script.

<script>
      $(document).ready(function () {
          $("#saveclick").click(function (e) {
              var FormCollection = {
                  StudentName: $("#name").val(),
                  StudentLastName: $("#last").val(),
                  StudentAddress: $("#address").val(),
                  Gender: $("#gender").val(),
                  StudentImage: $("#StudentImage").get(0).files,
              };

              $.ajax({
                  url:@Url.Action("Insert", "Student", null),
                  dataType: "json",
                  Type:"POST",
                  contentType: "application/json; charset=utf-8",
                  data: JSON.stringify({'FormCollection': FormCollection}),
                  success: function () {
                      alert("Data Saved Successfully");
                  },
                  error: function () {
                      alert("Please attach the Image");
                  }

              });
              return false;
          });
    });
</script>

And in the "Student" Controller this my action Method.

  [HttpPost]
  public ActionResult Insert(FormCollection fm)
  {

        Student s = new Student();
        s.StudentName = fm["StudentName"];
        s.StudentLastName = fm["StudentLastName"];
        s.StudentAddress = fm["StudentAddress"];
        s.Gender = fm["Gender"];
        HttpPostedFileBase file = Request.Files["StudentImage"];
        file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName);
        s.StudentImage = file.FileName;   
        db.Students.Add(s);
        db.SaveChanges();
        return RedirectToAction("Show");
  }
jmarkmurphy
  • 11,030
  • 31
  • 59
  • For this: `JSON.stringify({'FormCollection': FormCollection})`, you don't need to define anything for FormCollection - FormCollection essentially picks up all of the key/value pairs implicitly, so you want to just serialize the form or objects like: `$("#formid").serialize();` and let it be at that. – Brian Mains Jan 17 '17 at 13:25
  • Refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) for how to post a model including files using ajax (and never use `FormCollection` - use a view model and bind to your view model) –  Jan 17 '17 at 21:47
  • And using `return RedirectToAction("Show");` in a method that is called by ajax is pointless (ajax calls never redirect - the whole point of it is to stay on the same page) –  Jan 18 '17 at 03:19
  • didn't work. i tried these all. i'm stuck :( – Saqib Majeed Jan 18 '17 at 05:52
  • Of curse it works! (and if it did not work for you, then you did not follow the code correctly) –  Jan 18 '17 at 11:34

1 Answers1

0

can you change your jQuery AJAX code slightly and then try.

        $.ajax({
              url:@Url.Action("Insert", "Student", null),
              Type:"POST",
              data: new FormData( $( '#InsertForm' )[0] ),
              success: function () {
                  alert("Data Saved Successfully");
              },
              error: function () {
                  alert("Please attach the Image");
              }

          });
Ravi MCA
  • 2,491
  • 4
  • 20
  • 30