Failed to call action method using Ajax

2019-08-20 05:08发布

问题:

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)

回答1:

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.

$('#submitSignUp').click(function (e) {
    e.preventDefault();
    $.ajax({
        url: '@Url.Action("SignUp")',
        type: "POST",
        dataType: "json",
        data: $("#the_form_id").serialize(),
        success: function () {
            alert("Rgistered.");
        }
    });
});


回答2:

You can also do this way.

On your submitSignUp submit your parameter as following.

 var param = 
 {
    name: $('#name').val(),
    email: $('#email').val(),
    password: $('#password').val()
 };
 $.ajax({
        url: '@Url.Action("SignUp")',
        type: "POST",
        dataType: 'json',
        data: JSON.stringify(param),
        async: false,
        cache: false,
        traditional: true,
        contentType: 'application/json',
        success: function (data) {
            alert(1)
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert(errorThrown);
            return false;
        }
    });

Change your controller:

[HttpPost]
public ActionResult SignUp(string name, string email, string password)
{
  //other implementation
  return Json("", JsonRequestBehavior.AllowGet);
}

Hope this helps!



回答3:

Try this as your ajax method -

$('#buttonID').on("click",function() {
var data=
{
    var name = $('#name').val();
    var email = $('#email').val();
    var password = $('#password').val();
};
    $.ajax({
        url: '@Url.Action("SignUp","ControllerName")',
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        data: JSON.stringify(data),
        success: function () {
            alert("success");
        }
    });
});