Here's my JS (jQuery and Ajax) code:
$('#submitSignUp').click(function () {
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
url: '@Url.Action("SignUp")',
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify({ name: name, email: email, password: password }),
success: function () {
alert("Rgistered.");
}
})
})
and this is my action method. (It's in "Home controller"):
[HttpPost]
public JsonResult SignUp(string name, string email, string password)
{
TodoNet.Models.TodonetModel database = new TodoNet.Models.TodonetModel();
TodoNet.Models.User oUser = new TodoNet.Models.User()
{
FirstName = name,
LastName = name,
Email = email,
Password = password,
Salt = password,
IsDeleted = false,
IsOnline = false,
PhoneNumber = "09212131212",
RegisterDate = DateTime.Now,
LastLoginDate = DateTime.Now
};
database.Users.Add(oUser);
database.SaveChanges();
return new JsonResult();
}
but I don't know why it doesn't work. after clicking on the '#signUpSubmit' button, the "alert("Registered.")" will not be shown. What am I doing wrong??
Note: without using Ajax, (by using ordinary send form data to the action method, everything works properly (It means I know that there's nothing wrong with the back-end code)
If the form submitting normally works, then your ajax should be sending form data not json.
Also, prevent the default action of the button click.
Try this as your ajax method -
You can also do this way.
On your
submitSignUp
submit your parameter as following.Change your controller:
Hope this helps!