I have a controller with the following action code:
public JsonResult CheckPasswordStrength(string password, string username, string firstname, string lastname)
{
...
return this.Json(jsonResponse);
}
Then in my javascript on page I call
$.getJSON('http://localhost/site/controller/CheckPasswordStrength', { password: 'test', username: null, firstname: null, lastname: null }, function(data) {
...
});
The problem is that the parameters that are null (firstname, lastname, username) in my javascript call, they are not null in invoked controller action. They have string “null” value. I’ve already tried with undefined values of parameters in my javascript but it doesn’t help.
If I specify only parameters that are not null (without null parameters) in my javascript call, the parameters in my action are transferred correctly.
How should I pass null parameters in my $getJSON call that will be correctly transffered to controller action or what should I do on MVC side?
I’m assuming your building this object literal from the values of some form fields. Why not post empty strings instead? If you really want to leave values empty, don’t pass them at all, strip the nulls out of the data before sending:
Although I suggest against reaching into other peoples frameworks and overriding things – you could make the
$.paramfunction (which is what jQuery uses to turn your object into a query string) call stripNull automaticallyIf you would prefer to pass an empty string, or some other “null identifier” (say
\01for instance) you can still use stripNull() but changedelete obj[i];—obj[i] = '';