我应该将表单提交从 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 中,但它仍然不起作用。
谢谢你的帮助 :)