How to Receive Ajax Data values from Controller in asp mvc
asp.net-ajax, asp.net-mvc, c#, jquery
Solution
Your ActionResult is `GET` And you have no input parameter for your ActionResult so either change those or see below:
<script>
$('#inline-username').click(function () {
var comments = $('#inline-username').val();
//var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: /ControllerName/ActionName
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { test: comments },
success: function (data) {
// data is your result from controller
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
});
Then within your controller:
public ActionResult UpdateOrder(string test)
{
// some code
return Json(new { success = true, message = "Order updated successfully" }, JsonRequestBehavior.AllowGet);
}
Update
Remember if you want to use `POST` then action you are calling has to be `[HttpPost]` like:
[HttpPost]
public ActionResult Example()
When there is no HTTP above your ActionResult Then Its By Default `Get`.
Problem
using the following script, I am trying to access the variables being sent using data in the ajax function but I couldn't. ``` <script> $('#inline-username').click(function () { var comments = $('#inline-username').val(); //var selectedId = $('#hdnSelectedId').val(); $.ajax({ url: '@Url.Action("UpdateOrder")', // to get the right path to controller from TableRoutes of Asp.Net MVC dataType: "json", //to work with json format type: "POST", //to do a post request contentType: 'application/json; charset=utf-8', //define a contentType of your request cache: false, //avoid caching results data: { test: $(this).text() }, // here you can pass arguments to your request if you need success: function (data) { // data is your result from controller if (data.success) { alert(data.message); } }, error: function (xhr) { alert('error'); } }); }); ``` here is the action in the controller ``` public ActionResult UpdateOrder() { // some code var test = Request.Form["test"]; return Json(new { success = true, message = "Order updated successfully" }, JsonRequestBehavior.AllowGet); } ``` I tried `Request.Form["test"]` but the value of it is null. how should I receive the objects of `data`?