3

我应该将表单提交从 MVC Razor 提交转换为 Ajax 提交,但即使在表单视图(Add.cshtml)中使用简单的 JavaScript 函数,我也遇到了麻烦。

对于初学者,我尝试通过以下方式链接我想要使用的 JS 文件:

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/ajax_submit.js")"></script>
}

javascript 文件如下所示:

function dosubmit() {
    $("#add_address").ajaxForm({ url: '~/Home/Add', type: 'post' })
    alert("IT WORKS");
    return false;// if it's a link to prevent post
}

我的表单是按以下方式构建的:

@model MvcApplicationTest.Models.PersonModel
@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/ajax_submit.js")"></script>
}

@{
    ViewBag.Title = "Hinzufügen";
}



<h2>Hinzufügen</h2>


<form id="add_address">

    <div class="fieldrow">
        @Html.LabelFor(x => x.Nachname)
        @Html.TextBoxFor(x => x.Nachname)
        @Html.ValidationMessageFor(x => x.Nachname)
    </div>
    <div class="fieldrow">
        @Html.LabelFor(x => x.Vorname)
        @Html.TextBoxFor(x => x.Vorname)
        @Html.ValidationMessageFor(x => x.Vorname)
    </div>
    <div class="fieldrow">
        @Html.LabelFor(x => x.Strasse)
        @Html.TextBoxFor(x => x.Strasse)
        @Html.ValidationMessageFor(x => x.Strasse)
    </div>
    <div class="fieldrow">
        @Html.LabelFor(x => x.Hausnummer)
        @Html.TextBoxFor(x => x.Hausnummer)
        @Html.ValidationMessageFor(x => x.Hausnummer)
    </div>
    <div class="fieldrow">
        @Html.LabelFor(x => x.Plz)
        @Html.TextBoxFor(x => x.Plz)
        @Html.ValidationMessageFor(x => x.Plz)
    </div>
    <div class="fieldrow">
        @Html.LabelFor(x => x.Ort)
        @Html.TextBoxFor(x => x.Ort)
        @Html.ValidationMessageFor(x => x.Ort)
    </div>
    <!--Martin-->
    <div class="fieldrow">
        @Html.LabelFor(x => x.Email) 
        @Html.TextBoxFor(x => x.Email)
        @Html.ValidationMessageFor(x => x.Email)
    </div>

    <input type="button" onclick="dosubmit()" value="Speichern"  />
</form>

但是,当我单击该按钮时,什么也没有发生(它应该会弹出一个包含所需文本的窗口)。

我尝试将 JS 文件包含到 _Layout.cshtml 中,但它仍然不起作用。

谢谢你的帮助 :)

4

1 回答 1

1

.ajaxForm当文档准备好时,您应该只需要调用表单本身。.ajaxForm它本身只是为 ajax 提交准备表单,所以当提交按钮被按下时,已经为时已晚。

我会从submit按钮中删除提交处理程序(我也会在这里使用input类型submit):

<input type="submit" value="Speichern"  />

并添加以下内容:

$(function () {
    $("#add_address").ajaxForm({ 
        url: '~/Home/Add', 
        beforeSubmit: function () {
            alert('about to submit');
        },
        type: 'post' 
    });
});

或者,您可以使用.ajaxSubmit而不是.ajaxForm

function dosubmit() {
    $("#add_address").ajaxSubmit({ url: '~/Home/Add', type: 'post' });
    alert("IT WORKS");
    return false;// if it's a link to prevent post
}
于 2013-05-28T13:45:31.490 回答