Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read FormData into WebAPI

I have an ASP.NET MVC WebApplication where I am using the ASP.NET Web API framework.

Javascript code:

var data = new FormData();
data.append("filesToDelete", "Value");

$.ajax({    
    type: "POST",
    url: "/api/FileAttachment/UploadFiles?clientContactId=" + clientContactId,
    contentType: false,
    processData: false,
    data: data,
    success: function (result) {
        // Do something
    },
    error: function (xhr, status, p3, p4) {
        // Do something
    }
});

C# code (WebAPI):

public void UploadFiles(int clientContactId) {
    if (!Request.Content.IsMimeMultipartContent()) {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    var jsonContent = Request.Content.ReadAsStringAsync().Result;
}

How do I read jsonContent based on a key value pair passed by the Javascript FormData?

I tried to do JsonConvert.DeserializeObject<?>, but it requires a particular type to deserialize into.

I want to get the value of the key "filesToDelete" passed from the Javascript FormData.

How can I get this value?

like image 316
ghanshyam.mirani Avatar asked Nov 25 '16 05:11

ghanshyam.mirani


People also ask

What is FormData in API?

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the fetch() or XMLHttpRequest. send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data" .


1 Answers

Please use the below for get the value in the controller,

var filesToDelete = HttpContext.Current.Request.Params["filesToDelete"];
var clientContactId= HttpContext.Current.Request.Params["clientContactId"];
like image 130
Aravindkumar Murugesan Avatar answered Sep 20 '22 20:09

Aravindkumar Murugesan