0

How can I POST <input type="file" id="uploadStudent" /> uploaded file to mvc controller in this scenario?

Javascript

$.ajax({
  url: "/Home/CompleteAttendeeType",
  contentType: "application/json;charset=utf-8",
  dataType: "JSON",
  type: "POST",
  data: JSON.stringify({
    //PostedFile: "I AM CONFUSED HOW TO UPLOAD?",
    AttendeeType: 1,
    LicenseNumber: $("#txtLicenseNumber").val(),
    LicenseState: $("#txtLicenseState").val(),
    SchoolName: $("#txtSchoolName").val(),
    SchoolLocation: $("#txtSchoolLocation").val()
  })
})

MVC

[HttpPost]
public JsonResult CompleteAttendeeType(CompleteAttendeeTypeRequest request)
{
  return Json(string.Empty, JsonRequestBehavior.AllowGet);
}

public enum AttendeeType
{
  Professional,
    Student,
    Owner,
    Guest
}

public class CompleteAttendeeTypeRequest
{
  public HttpPostedFile PostedFile { get; set; }
  public AttendeeType AttendeeType { get; set; }

  public string LicenseNumber { get; set; }
  public string LicenseState { get; set; }

  public string SchoolName { get; set; }
  public string SchoolLocation { get; set; }
}
jahller
  • 2,705
  • 1
  • 28
  • 30
SOF User
  • 7,590
  • 22
  • 75
  • 121
  • 1
    You can use `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) for an example –  Oct 12 '15 at 09:19
  • @StephenMuecke — That won't give JSON output – Quentin Oct 12 '15 at 10:40
  • @Quentin, Not sure what your saying. OP can either serialize a form or add each property individually - e.g. `formdata.append(LicenseNumber, $("#txtLicenseNumber").val());` etc which will bind to the `CompleteAttendeeTypeRequest` model in the controller. –  Oct 12 '15 at 10:45
  • @StephenMuecke — The request is being formatted as application/json not multipart/form-data. You can't get application/json out of FormData objects. – Quentin Oct 12 '15 at 10:45
  • OP want to upload a file and properties so that they can be bound to a model. It does not need to be _JSON output_ - but it does need to work which is what the linked answer does :) –  Oct 12 '15 at 10:48

1 Answers1

0

First use the File API to read the contents of the file.

Then you need to express the data in a format that can be represented in JSON. If the data is a string, then you can just use that. Otherwise, you will need to convert it. Converting it to base64 is one approach.

Then you'll have data in a variable that you can include in the object you pass to JSON.stringify.

If you encoded it as base64, you'll need to decode it on the server.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335