ASP .net不会触发提交事件

时间:2016-09-07 15:29:40

标签: javascript jquery asp.net ajax asp.net-ajax

我尝试使用ASP .net和jquery提交ajax,但是他从未尝试过这个事件,我已经尝试过这两个例子并且他从未触发事件警报。

<form id="form">
    <div class="row">
        <div class="col-sm-6">
            <div class="form-group">
                @Html.TextBoxFor(m => m.VatNumber,new { @class = "form-control", @id="VatNumber"})
                @Html.ValidationMessage("VatNumber")
             </div>
        </div>
        <div class="col-sm-6">
             <div class="form-group">
                <input type="submit" class="btn btn-primary" value="Check VAT" />
            </div>
        </div>
   </div>
</form>
<script type="text/javascript">
    $(document).ready(function () {
        $('#form').submit(function () {
            alert("cheguei");

            $.ajax({
                url: '@Url.Action("CheckVat")',
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({
                    VatNumber: $('#VatNumber').val(),
                }),
                success: function (result) {
                    alert("success");
                },
                error: function (result) {
                    alert("error");
                }
            });
          return false;
        });
    });
    $(function () {
        $('#form').submit(function (event) {
            alert("cheguei");
            event.preventDefault(); // Prevent the form from submitting via the browser
            var form = $(this);
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize()
            }).done(function (data) {
                // Optionally alert the user of success here...
            }).fail(function (data) {
                // Optionally alert the user of an error here...
            });
        });
    });
</script>

1 个答案:

答案 0 :(得分:0)

我弄清楚:我必须在Head部分包含脚本,问题已解决。

<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title - My ASP.NET MVC Application</title>
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <meta name="viewport" content="width=device-width" />
    @Styles.Render("~/Content/bootstrap.min.css")
    @*@Styles.Render("~/Content/css")*@
    @Scripts.Render("~/bundles/modernizr")
           <script src="~/Scripts/jquery-3.1.0.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
</head>