简体   繁体   English

Ajax向控制器发送空字符串?

[英]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 我正在使用ajax调用尝试向我的控制器发送字符串,但它返回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 和我的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. dataType选项定义了预期的响应类型,而不是您要发送的数据的类型。 For that, you need contentType , which needs an actual mime type, ie text/plain rather than just "text". 为此,您需要contentType ,它需要一个实际的mime类型,即text/plain而不只是“ 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. 最后,在您的操作中,默认绑定类型是x-www-form-urlencoded ,它需要一个键值对。 You can change data again to: 您可以再次将data更改为:

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 : 您将在操作参数上收到的参数名称为itemText ,然后需要将数据配置为data: {itemText: boxText } ajax中的data: {itemText: boxText }以绑定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"),
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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