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