Ajax PUT request to Web Api

3.3k views Asked by At

I currently have a ajax request setup to send a "PUT" request to a web api in my mvc 4 project. My request is able to get into the method on the api but the parameter is always null. Any ideas why? I have also check the PUT request as its executed and it does send a string of key/value pairs for each form control. Here is my code:

Web Api method (selection is always null)

public void Put([FromBody]string selection)
{
}

Update:

I forgot I was doing a little debugging of my own. I have confirmed that when you serialize a form the param is named "selection". Please take another look.

Ajax call:

$.ajax({
    type: "PUT",
    url: urlPrefix + "api/file/Manipulate",
    data: $("#frmManipulate").serialize(),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    statusCode: {
        204: function (jqXHR) {
            alert("No file(s)/Directory(s) were selected.");
        }
    }
}).done(function () {
    location.reload();
});
2

There are 2 answers

0
Ant P On

It's null because you aren't passing it:

data: { val1 : "test",  val2 : "test2"}

Try:

data: { selection : "something" }
0
Felipe Oriani On

It is null because asp.net web api does not know how to deserialize the { val1 : "test", val2 : "test2"} to a string. You could use a DTO approuch to pass these information to the action, for sample:

in the web api project, add a class like this:

public class InfoDTO
{
    public string val1 { get; set; }
    public string val2 { get; set; } 

    // other properties if you need
}

And change your put action to get a parameter with this type:

public void Put([FromBody]InfoDTO info)
{
   // use 'info' object
}

Your client-side javascript can keep with the same code.