Register new users in an asp.net application without a form

82 views Asked by At

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.

1

There are 1 answers

0
Najkin On BEST ANSWER

On AccountController every action needs to return an ActionResult object, or in the case of an async action, a Task<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:

public async Task<ActionResult> Register(UserItem post) {

and instead of returning true or false, return Json(true) or Json(false)