0

I am trying to send file and a few parameter values via ajax call, using formData, to Web api. Here is my ajax call.

    var dataToPost = new FormData();
    dataToPost.append("file", file);
    dataToPost.append("placeId", "1");

    $.ajax({
        type: "POST",
        url: "/api/Post/SharePost",
        processData: false,
        contentType: false,
        dataType: "json",
        data: dataToPost,
        success: function () { },
        error: function () {}
    });

And here is my web api controller

    [HttpPost]
    public IHttpActionResult PostSharePost(HttpPostedFileBase file, string placeId)
    {
        //var file2 = HttpContext.Current.Request.Files["file"];
        //var placEId = HttpContext.Current.Request["placeId"];

        return null;
    }

When I execute the ajax, I can retrieve the data from Request.Files["file"] and Request["placeId"]. But I want to map the data to the method's parameters. But when I add parameters to "PostSharePost" method, the ajax call returns 404 error. How can I map the data to parameters in web api controller's method?

Because It works fine when I do the same thing with mvc controller like when I send ajax call with the same setting to mvc controller as the following

    [HttpPost]
    public ActionResult SharePost(HttpPostedFileBase file, string placeId)
    {
        //here the data maps to file and placeId
        return null;
    }

Why ajax call to mvc controller and web api controller behaves differently and how can I map the data to web api controller's parameters?

Thanks guys;

Michael
  • 63
  • 2
  • 2
  • 9
  • Model binding in Web API is fundamentally different than in MVC – Mindless Mar 16 '17 at 05:36
  • @Mindless So there is no way to bind the data to parameters in web api controller? – Michael Mar 16 '17 at 05:37
  • [See this](http://stackoverflow.com/questions/12697310/web-api-model-binder-doesnt-work-with-httppostedfilebase) and [This](http://stackoverflow.com/questions/12901905/is-it-possible-to-have-modelbinding-in-asp-net-webapi-with-uploaded-file) – Mindless Mar 16 '17 at 05:39

0 Answers0