无法使用Ajax调用操作方法 [英] Failed to call action method using Ajax

查看:168
本文介绍了无法使用Ajax调用操作方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的JS(jQuery和Ajax)代码:

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();
    }

但是我不知道为什么它不起作用.单击"#signUpSubmit"按钮后,将不会显示"alert(已注册."). 我在做什么错??

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??

注意:在不使用Ajax的情况下(通过使用普通的将表单数据发送到action方法的方法,一切都可以正常工作(这意味着后端代码没什么问题)

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)

推荐答案

如果表单提交正常工作,则您的ajax应该发送的是表单数据,而不是json.
另外,请阻止按钮单击的默认操作.

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.");
        }
    });
});

这篇关于无法使用Ajax调用操作方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆