Domanda

You'd think: how hard can this be? Well, Quite it seems.

jQuery running:

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/api/TEST",
            data: {"":{close:true, user: "<%: uuid %>" }},
            success: null,
            dataType: "json"
        });

I am using asp.net webforms with the ApiContoller trying to post some simple data.

public class TESTController : ApiController {
    // GET api/<controller>
    public IEnumerable<string> Get() {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    public string Get(int id) {
        return "value";
    }

    // POST api/<controller>
    public void Post([FromBody]string value) {
        string k = ";;";


    }

    // PUT api/<controller>/5
    public void Put(int id, [FromBody]string value) {
    }

    // DELETE api/<controller>/5
    public void Delete(int id) {
    }
}

the POST method gets called, but the value is always null. I've tried changing the data in the ajax post without the empty quotes before it, to no avail.

È stato utile?

Soluzione

Apparently after browsing through blogs for hours this is all you need to do / edit in the above example:

public string Post(tester test) {
    string k = ";;";

    return k;
}

add a class

public class tester {
    public string user { get; set; }
    public bool close { get; set; }
}

and change the AJAX to

    var value = {close:true, user: "<%: uuid %>" };
    $.ajax({
        type: "POST",
        contentType: "application/json;charset=utf-8",
        url: "/api/TEST/",
        data: JSON.stringify(value)
    }).done(function(msg) {
        alert("done"+msg); 
    });
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top