I would like to register new users in an asp.net application. Instead of using a form I would like to use Ajax.
This is my post function in my AccountController:
[System.Web.Mvc.HttpPost]
public async Task<bool> Register(UserItem post) {
try {
var user = new ApplicationUser { UserName = post.UserName, Email = post.UserName };
var result = await UserManager.CreateAsync(user, post.Password);
if (result.Succeeded) {
post.Id = user.Id;
await _userRepository.Save(post);
return true;
}
AddErrors(result);
}
catch (Exception e) {
Console.WriteLine(e);
}
// If we got this far, something failed, redisplay form
return false;
}
And this is my Ajax call to my controller:
var userJson = ko.toJSON(self.selectedUser);
console.log(userJson);
$.ajax({
type: "POST",
url: "http://localhost:7061/Account/Register",
headers: "application/json; charset=UTF-8",
dataType: "json",
contentType: "application/json",
data: userJson,
error: function (xmlHttpRequest, textStatus, errorThrown, response) {
},
success: function (response) {
console.log(response);
self.loadUsers();
}
});
But my register function in the controller never gets called.
Thanks.
On
AccountController
every action needs to return anActionResult
object, or in the case of an async action, aTask<ActionResult>
. Otherwise, it won't be seen as an action, and no request will be routed to it.Change the signature of the method to:
and instead of returning
true
orfalse
, returnJson(true)
orJson(false)