taiko taiko - 3 months ago 39
Ajax Question

Get variables from ajax request in code behind

So, some time ago, I needed to make ajax requests to access the code behind. I did that (here).

But now I'm working on asp.NET Core 2.0 and it works differently. Well, now I can make a request but, for some reason The variables are null (only on the code behind, on the client side they have content. Probably isn't a big deal, but I can't grasp why.

So, here's my ajax function:

function Ajax(expression1, expression2, url, json, error) {
console.log(expression1+" - "+ expression2);
var request = { email: expression1, password: expression2 }

url: url,
method: 'post',
contentType: 'application/json',
data: JSON.stringify(request),
dataType: 'json',
success: function (resp) {
if (expression1 === null || expression2===null)
window.location.href = resp[json];
document.getElementById(error).innerHTML = resp[json];
error: function (error) {

And the c# code:

public string ExternalLogin(string email, string name)
//TODO: Facebook login

// Redirect link example. Could be another one.
return "{\"facebook\":\"Home/About\"}";

The ajax function makes the request and it triggers the c# function, and returns what I ask it to. The only problem is the null variables. Why is this happening?

EDIT: The User class as requested:

public class User
[JsonProperty(PropertyName ="email")]
public string Email { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "password")]
public string Password { get; set; }

Answer Source

The parameter binding fails because you are making a post request here. You have to add the [FromBody] attribute to your parameters.

You can get more info about paramter binding here:


You also passing a object as paramter so you either have to change you route paramter to an object containing email and password property, or you change your Content-Type to 'application/x-www-form-urlencoded' and pass a query string like 'email=....&password=....'

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download