12

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?

Kelvin
  • 320
  • 4
  • 19
ghanshyam.mirani
  • 3,075
  • 11
  • 45
  • 85
  • Add a parameter `[FromBody]string filesToDelete` to your method assuming your really are passing a string –  Nov 25 '16 at 05:20

6 Answers6

16

What I would Do is:

Client Side: Instead of passing clientContactId in query string. Attach the key value pair in the FormData object itself. Set the dataType as JSON.

var data = new FormData();
data.append("filesToDelete", "Value");
data.append("clientContactId", 
(clientContactId != undefined || clientContactId != null) ? clientContactId : ''));

$.ajax({
        type: "POST",
        url: "/api/FileAttachment/UploadFiles",
        /* ONLY IF YOU ARE UPLOADING A FILE
        contentType: false,
        processData: false, */
        dataType: "JSON"
        data: data,
        success: function (result) {

        },
        error: function (xhr, status, p3, p4) {


        }
    });

Server Side: At server side we can get the raw request using HttpContext.Current.Request.

So we can get the values by simply using the key values of FormData object inside HttpContext.Current.Request.Params["KeyValue"].

[HttpPost]
public void UploadFiles()
{
     var filesToDelete = HttpContext.Current.Request.Params["filesToDelete"];
     var clientContactId= HttpContext.Current.Request.Params["clientContactId"];

     //Your code here...
}
Ajay2707
  • 5,690
  • 6
  • 40
  • 58
Shahbaaz
  • 403
  • 5
  • 11
  • can you please help me to solve this https://stackoverflow.com/questions/53003264/how-to-receive-form-data-and-process-the-data-in-wen-api @Ajay2707 – Zhu Oct 26 '18 at 07:07
3

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"];
balint
  • 3,391
  • 7
  • 41
  • 50
1

I think this tutorial from the ASP.NET website might be what you are looking for:

Sending HTML Form Data in ASP.NET Web API: Form-urlencoded Data

Based on your sample code I'm not sure if you need a complex type from the form data or just a single integer based on the UploadFiles(int clientContactId) method in your API Controller. The signature makes it seem like you're just trying to pass a single integer. If that is the case, your API Controller method could look like this:

[HttpPost]
public void UploadFiles(int clientContactId)
{
    //access the 'clientContactId' input parameter
    int id = clientContactId;
}

And your AJAX call will look something like this:

$.ajax({
    url: '/api/controller/UploadFiles', //your app url
    type: 'POST',
    data: { clientContactId: 12345 },
    dataType: 'json',
    success: function (result) {
        //do whatever
    },
    error: function (result) {
        //do whatever
    }
});

If you already have the data formatted as JSON in your JavaScript, you can send it in the body of the requests. The Controller method could look something like this:

[HttpPost]
public void UploadFiles([FromBody] MyComplexType input)
{

}

And your AJAX call could look like:

$.ajax({
    url: '/api/controller/UploadFiles', //your app url
    type: 'POST',
    data: JSON.stringify(input),
    dataType: 'json',
    success: function (result) {
        //do whatever
    },
    error: function (result) {
        //do whatever
    }
});

Check out the tutorial I linked to above though, I think that may explain things a bit better for you.

mfcallahan
  • 165
  • 4
  • 17
0

If you want to send data with JSON like that you should define a model in C# that matches the model you're passing back in JSON. Your WebApi controller method will look something like this:

    public HttpResponseMessage Post([FromBody]WorkerAbsenceModel absence)
    {
        bool ok = svc.CreateWorkerAbsence(absence);
        if (ok)
        {
            return Request.CreateResponse(HttpStatusCode.OK);
        }

        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
AndrewWhalan
  • 417
  • 3
  • 12
0

To get the "filesToDelete" value you can use JSON.NET. the code:

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

            JObject jObject = JObject.Parse(jsonContent);
            var filesToDelete = jObject["filesToDelete"];    
        }  
user1567453
  • 1,837
  • 2
  • 19
  • 22
0

You can create dynamic object

dynamic data = JsonConvert.DeserializeObject(jsonContent);

then you can access filesToDelete like

data.filesToDelete;
Mostafiz
  • 7,243
  • 3
  • 28
  • 42