从Razor表单提交调用JS方法

时间:2016-12-18 09:53:23

标签: javascript c# jquery razor

当我提交表单时,我想启动下面写的Javascript方法。此JS方法将向后端发送POST请求。但是,在下面编写的代码中,此JS方法未被触发。有人可以帮我解决这个问题吗?

@using (Html.BeginForm(null, null, FormMethod.Post, new { @class = "form-horizontal",  onsubmit = "submitdata" }))
{
    @Html.AntiForgeryToken()

    @Html.ValidationSummary()
    <div class="form-group">
        @Html.LabelFor(m => m.EMAIL, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.email,  new {id ="Email", @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.pwd, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.pwd, new {id="pwd", @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" onsubmit="submitdata"/>
        </div>
    </div>
}

的Javascript

function submitdata() {
    var pwd = document.getElementById("pwd");
    var email = document.getElementById("email");

    $.ajax({
        type: 'post',
        url: '/Account/Reg',
        data: {
            email: email,
            password: pwd
        },
        success: function (response) {
            $('#success__para').html("You data will be saved");
        }
    });

    return false;

}

2 个答案:

答案 0 :(得分:1)

你的onsubmit属性中的miss();

onsubmit = "submitdata()"

答案 1 :(得分:0)

正如Vostrugin在他的回答中提到的,你在方法调用中缺少()

这是unobtrusive javascript方式(使用jQuery)

function submitdata() {
   // your existing code
}
$(function(){
  $("form").submit(function(e){
     e.preventDefault();
     submitData();
  });
});

如果要使用特定按钮单击连接它,请使用jQuery选择器获取按钮并绑定click事件。

<input type="submit" id="myButton" value="Register"/>

$(function(){
  $("#myButton").click(function(e){
     e.preventDefault();
     submitData();
  });
});

使用此方法,您应该从UI标记中删除onsubmit事件。