-1

I am new to ajax, am trying to send username value to Answer function then return it back to the view , but i get undefined no matter what i tried.

//Answer function from the HomeController.cs

        [HttpPost]
       public string Answer(string userName)
       {


            return userName;
        }

//ajax call from the view

        $.ajax({
        type: "POST",
        url: "/Home/Answer",
        contentType: "application/json; charset=utf-8",
        data: '{"userName":"' + message + '"}',
        dataType: "html",
        success: function (result, status, xhr) {
            alert(message);

            outputArea.append(`
      <div class='user-message'>
        <div class='message'>
          ${result}
        </div>
      </div>
    `);
        },
        error: function (xhr, status, error) {
            alert("Something went wrong");
        }
    });
tereško
  • 58,060
  • 25
  • 98
  • 150
  • 1
    Look into `[FromBody]` – Stuart Aug 14 '19 at 12:24
  • 1 Have you put a break point in `Answer`. Is it being called and is the parameter correct? 2 The `message` in your alert is not defined. – Peter Smith Aug 14 '19 at 12:30
  • __OT__ `data: '{"userName":"' + message + '"}'` don't form JSON by hand, this will break if there's a `"` anywhere in `message`. Use `data: {"userName":message}` or `data: JSON.stringify({"userName":message})` instead. – phuzi Aug 14 '19 at 12:43

2 Answers2

1

Specific to your case, you can refer to this code snippet to get your required data:

<script>


//Now generate your JSON data here to be sent to the server
  var json = {
              messageVariable: message
             };

//Send the JSON data via AJAX to your Controller method
    $.ajax({
        url: '@Url.Action("Answer", "Home")',
        type: 'post',
        dataType: "json",
        data: { "json": JSON.stringify(json)},
        success: function (result) {
                  console.log(result);
        },
        error: function (error) {
             console.log(error)
        }
      });
</script>

And your Controller will look like:

using System.Web.Script.Serialization;

[HttpPost]
public ActionResult Answer(string json)
{

        var serializer = new JavaScriptSerializer();
        dynamic jsondata = serializer.Deserialize(json, typeof(object));

        //Get your variables here from AJAX call
        var message= jsondata["messageVariable"];

        //Do something with your variables here.

    return Json(new { success = true, messageVariable }, JsonRequestBehavior.AllowGet);
}
Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
0

Do what @Stuart told you in the comments about adding the FromBody attribute as:

[HttpPost]
public string Answer([FromBody] string userName)
{
   return userName;
}

or use data: JSON.parse('{"userName":"' + message + '"}') to your json.

André Silva
  • 1,149
  • 9
  • 30
  • tryed both but still no result –  Aug 14 '19 at 12:40
  • This will sound crazy, but try `data: '=' + '{"userName":"' + message + '"}'`, I used to get a lot of problems with json strings when I posted without adding the equal sign before the json... – André Silva Aug 14 '19 at 12:46
  • yes but had problems with the System.Web.Script.Serialization spacename –  Aug 16 '19 at 16:23
  • @DhiaTr That is simple to resolve. You can either add the reference manually from Add Reference in Visual Studio. You can refer to this link to add the reference: https://stackoverflow.com/questions/1156313/adding-system-web-script-reference-in-class-library – Rahul Sharma Aug 16 '19 at 20:22
  • had some problems adding the library, after researching it appears that is a problem in vs19 else all the code worked when i changed to vs15 –  Aug 17 '19 at 15:29
  • Mark his answer as the correct one by clicking the checkmark within his response. That will help others in the future :) – André Silva Aug 20 '19 at 11:27