0

I Want to send formData to api controller via jquery ajax. This is My code in view:

$("#btnReject").click(function() {
  UploadData = new FormData();
  UploadData.append('UserName',$("#txtUserName").val());
  // HTML file input, chosen by user
  UploadData.append("userfile", fileInputElement.files[0]);
  $.ajax({
     url: 'Api/DynamicForm/Reject',
     dataType: "json",
     type: "post,
     contentType: false,
     processData: false,
     data: UploadData
  });
}

and my controller code:

public class DynamicFormController : ApiController
{
    [System.Web.Http.HttpPost]
    public IHttpActionResult Reject (DynamicFormDto model)
    {
       //some code
        return Json(new isValid = true});
    }
}

In DynamicFormDto:

Public class DynamicFormDto
{
   public string UserName {get; set;}
   public string Model {get; set;}
}

I encountered with this error in client side: 415 : Unsupported Media Type

when I remove "contentType: false" error fixed but in action "model" is null.

What should I do?

Sina Razavi
  • 45
  • 3
  • 9
  • The ModelBinder has issues with binding multipart requests to complex types (in that it doesn't work). See the duplicate I marked for more information. Also note that you could instead write your own custom model binder instead, [see this answr](https://stackoverflow.com/a/12603828/519413) for how to achieve that – Rory McCrossan Apr 04 '18 at 08:20
  • @RoryMcCrossan, Did you pick the wrong dupe target? (that has nothing to do with OP's question - they are already using `FormData`) –  Apr 04 '18 at 09:22

1 Answers1

0
 public class DynamicFormController : ApiController
{
    [System.Web.Http.HttpPost]
    public IHttpActionResult Reject ()
    {

      var name = HttpContext.Current.Request["UserName"];
      var httpPostedFile = HttpContext.Current.Request.Files["userfile"];
    //some code

        return Json(new isValid = true});
    }
}
Min
  • 1