This is a fairly recurring theme on StackOverflow, but once again I can’t get my MVC controller action to recognise the data I’m trying to send. Any suggestions gratefully received.
My controller action looks like this:
[Authorize]
[HttpPost]
public JsonResult Record(int task, string notes, double hours)
{
Repository<TimeEntry> TimeRepo = new Repository<TimeEntry>();
...
My Ajax call looks like this:
var Task = $('#time-task option:selected').val();
var Hours = parseFloat($('#time-hours').val());
var Notes = $('#txtNotes').val();
if (isNaN(Hours)) {
Hours = 0;
}
$.post('/Home/Record', { task: Task, notes: Notes, hours: Hours }, function (data) {
console.log(data);
});
And the exception returned is:
The parameters dictionary contains a
null entry for parameter ‘task’ of
non-nullable type ‘System.Int32’ for
method ‘System.Web.Mvc.JsonResult
Record(Int32, System.String, Double)’
in
‘JobTrack.Controllers.HomeController’.
An optional parameter must be a
reference type, a nullable type, or be
declared as an optional
parameter.
Parameter name:
parameters
There has to be something basic I’m overlooking, but damned if I can figure out where I’m going wrong. Suggestions appreciated.
Update: So changing the $.post to a $.ajax call and having that call use GET instead of POST appears to work. I suppose I can live with that but I’d rather be doing this correctly. Any suggestions as to why the HTTP Verbs should be making a difference?
ARGH!
Knew it would be something basic I’d overlooked.
The root cause of the problem was the /Scripts/globals.js file that I haven’t even been looking at (and had pretty much forgotten completely about). In that, I had the following code:
The problem? ContentType. My understanding of the root cause is that since I’m using jQuery 1.4, the content type is being correctly determined automatically (“application/x-www-form-urlencoded”) and expressly defining it again in the global settings must confuse things somehow.
Thanks for all who contributed to this solution. If anyone knows why the contentType causes Ajax posts to fail in jQuery, I’d love to get a deeper understanding.