Craig Craig - 22 days ago 8
Javascript Question

$.ajax working, but $.post fails

I am trying to use the short hand version of posting data. My old way worked. I'm not understanding why the new way is not working.

On my controller, all the values are NULL. But in the old working version, they parsed fine.

Working:

$.ajax({
url: 'api/User/Register',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
EmailAddress: self.RegisterEmailAddress(),
Password: self.RegisterPassword(),
TimeZoneID: self.RegisterTimeZoneID(),
Firstname: self.RegisterFirstname(),
Surname: self.RegisterSurname()
}),
dataType: 'json'
}).done(function (data) {
alert(data);
});


Not working:

var registerdata = JSON.stringify({
EmailAddress: self.RegisterEmailAddress(),
Password: self.RegisterPassword(),
TimeZoneID: self.RegisterTimeZoneID(),
Firstname: self.RegisterFirstname(),
Surname: self.RegisterSurname()
});

var uri = 'api/User/Register';

$.post(uri, registerdata)
.done(function(data){
alert(data);
});


What is incorrect with the new version?
Note, as I post, the header has the correct data:

{"EmailAddress":"me@here.com","Password":"password","TimeZoneID":"4","Firstname":"Test","Surname":"Users"}:


On my controller the api looks like this:

[HttpPost]
public string Register(UserRegistrationRequestDto register)
{
var reply = _userService.Register(register);
return $"{reply.FriendlyMessage}";
}


And the UserRegistrationRequestDto is defined as:

public class UserRegistrationRequestDto : BaseRequestDto
{
public string EmailAddress { get; set; }
public string Password { get; set; }
public int TimeZoneID { get; set; }
public string Firstname { get; set; }
public string Surname { get; set; }
}


I can't see why the short version isn't working.

Note, a different call worked 100%

var logindata = JSON.stringify({
EmailAddress: self.LoginEmailAddress(),
Password: self.LoginPassword()
});

var uri = 'api/User/Login'

$.post(uri, logindata)
.done(function (data) {
alert(data);
});

Answer

You can pass settings to .post like this:

$.post({url: uri, contentType: "application/json", data: registerdata});