Reputation: 31
I am using JQuery Ajax to make a simple call to an ASP.NET MVC controller. Here is my code
function postdata(idno) {
console.log(idno);
$.ajax({
type: 'POST',
url: "/IM/GetMessages",
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ 'fUserId': idno }),
success: function (data) { /*CODE*/
});}
The controller looks like this
[HttpPost]
public ActionResult GetMessages(decimal? fUserId)
{
var list = WebUtility.IMMessages.Where(p =>
(p.ToUserId == Session.UserId && (!fUserId.HasValue || fUserId.HasValue && p.User == fUserId.Value)))
.OrderBy(p => p.CreatedDateTime)
.Select(p => new { MessageId = p.RecordId, MessageBody = p.Description1 });
return Json(list, JsonRequestBehavior.AllowGet);
}
The problem is that my data doesn't pass to my controller, "null" passes instead. how can I correct this issue? I am watching "idno" on console and everything seems to be OK.
Upvotes: 3
Views: 2746
Reputation: 31
I changed nothing with my code, but it is working now. I think there was another problem affecting passing data. I changed many things generally in my code and now actually i don't know what the problem exactly was. Maybe the solution was just rebooting my web application and clearing all caches and cookies in web browser.
Upvotes: 0
Reputation: 13223
There is no reason to convert a single parameter into a JSON if you ask me. Instead just do this:
$.ajax({
type: 'POST',
url: "/IM/GetMessages?fUserId=" + idno,
dataType: 'json',
success: function (data) { /*CODE*/
});
This way you can still get back JSON but you pass single parameter value. Now if you really need to send an object I don't see anything wrong with your code. You might want to declare a javascript variable and turn it into a json object like this:
var myVar = { fUserId: idno };
and then use that in your ajax request:
$.ajax({
type: 'POST',
url: "/IM/GetMessages",
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(myVar),
success: function (data) { /*CODE*/
});
I do this daily and it works fine for me with both nullable and non-nullable types...
Upvotes: 1
Reputation: 447
A quick search found a lot of materials on Stack Overflow relating to this issue. Pulled from this answer, try changing this:
data: JSON.stringify({ 'fUserId': idno }),
to this:
data: "fUserId=" + JSON.stringify(idno),
Upvotes: 1