简体   繁体   中英

Ajax sending null string to controller?

I'm using an ajax call to try to send a string to my controller but it is returning null

My controller

[HttpPost]
public async Task<string> CreateCarouselItem(string itemText){
    var newItem = new CarouselItem(itemText);
    await CarouselHelper.AddAndSaveAsync(newItem, _context);

    return itemText;
}

And My javascript

function FinishUp()
{
editor.disable();
var boxText = editor.getText();

$.ajax({
    type: "POST",
    url: '/Home/CreateCarouselItem',
    dataType: "text",
    data: { boxText },
    traditional: true,
    success: function (data) {
        console.log(data);
    },
    error: console.log("it did not work"),
});

}

The dataType option defines the expected response type, not the type of the data you're sending. For that, you need contentType , which needs an actual mime type, ie text/plain rather than just "text".

Then, you're sending an object instead of a string. If you just want the string then you should have just:

data: boxText

(without curly braces)

Finally, in your action, the default binding type is x-www-form-urlencoded , which expects a key value pair. You can change data again to:

data: 'itemText=' + boxText

Or you can bind from the body instead:

public async Task<string> CreateCarouselItem([FromBody]string itemText)

However, for that, I believe you also need to enable the text serializer in startup:

services.AddMvc(o =>
{
    o.InputFormatters.Add(new TextInputFormatter());
});

The name of the parameter which you would receive on action parameter is itemText , then you need to configure you data as data: {itemText: boxText } in ajax to bind the itemText :

$.ajax({
        type: "POST",
        url: '/Home/CreateCarouselItem',
        dataType: "text",
        data: {itemText: boxText },
        traditional: true,
        success: function (data) {
            console.log(data);
        },
        error: console.log("it did not work"),
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM