B
B
bullock2017-11-28 12:28:21
JavaScript
bullock, 2017-11-28 12:28:21

How to send data using ajax to asp .net core application?

Good day. The problem is that data from the js script is not transferred to the application,
here is the script code:

$.ajax({
    type: 'POST',
    url: 'Home/MessageHandler',
    data: "Test msg",
    success: function (data) {
        if (data == true) {
            alert("Сообщение доставлено");
            location.reload();
        }
        else {
            alert("Внимание! Сообщение не доставлено!");
        }
    },
    error: function () {
        alert("Произошел сбой");
    }
});


When launched, it goes to alert("Attention! Message not delivered!");

Here is the controller code that should handle the message:
[HttpPost]
public JsonResult MessageHandler(string data)
{
    Debug.WriteLine($"\n\nMessageHandler data: {data}\n\n");
    string result = "Сообщение " + data;
    return Json(result);
}

What could be the problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Kovalsky, 2017-11-28
@dmitryKovalskiy

Your POST request is waiting for an input parameter named data. And he doesn't know where to get it from.
1) Decide where you will fetch the data from and after you decide - add the "FromBody" or "FromUri" attribute to the parameter.
2) Then edit the code of the request itself in which you will send an Ajax request in which there will be a Json object of the structure {'data': value}

B
bullock, 2017-11-28
@bullock

I solved the problem by rewriting the controller like this:

public Object MessageHandler()
    {

        StreamReader sr = new StreamReader(Request.Body);
        string data = sr.ReadToEnd();

        string result = "Сообщение " + data;
        return result;
    }

Script:
$.ajax({
    type: 'POST',
    url: 'Home/MessageHandler',
    data: "Test msg данные тут",
    success: function (data) {
        console.log(data)
    },
    error: function () {
        alert("Произошел сбой");
    }
});

Everything works but I'm not sure if I did everything right.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question