0

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"),
});

}
1
  • Sending up boxText and looking for itemText? Commented Aug 22, 2019 at 19:39

2 Answers 2

1

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, i.e. 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());
});
Sign up to request clarification or add additional context in comments.

2 Comments

So I changed dataType to contentType and swapped "text" for "text/plain" as well as fixing data like you mentioned and its still coming back null. If i add the [FromBody] it becomes a 415 status code. And I'm not able to instantiate the TextInputFormatter because it's an abstract class
Sorry about that. I never actually had a need to accept plain text. You can simply create a concrete class that inherits from that, and then new up the concrete class. However, your best bet is to simply let it come as x-www-form-urlencoded and send data: "itemText=" + boxText.
0

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"),
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.