gpt4 book ai didi

javascript - Bootstrap 4 使用 JSON 进行模态验证

转载 作者:行者123 更新时间:2023-12-02 22:23:49 25 4
gpt4 key购买 nike

在单击/提交表单之前,我需要验证 TextBoxFor,我已经尝试了多种方法,但仍然无法使其工作。

模态:

<div class="modal fade" id="MyModal_C">
<div class="modal-dialog" style="max-width: 300px">
<div class="modal-content">
<div class="modal-header">
<h4 id="ModalTitle"></h4>
</div>
<div class="modal-body">
<form id="form">
<fieldset id="SubmitForm">

<div class="form-group">
@Html.LabelFor(x => x.Item2.Name, htmlAttributes: new { @class = "control-label" })
@Html.TextBoxFor(x => x.Item2.Name, new { @id = "Name", @class = "form-control", @placeholder = "Name*", @required = "required" })
</div>

<div class="form-group">
<a href="#nav-text" class="btn btn-block btn-danger" id="SaveRecord">SAVE</a>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>

JSON 帖子:

<script>
$("#SaveRecord").on('click', (function () {
var data = $("#SubmitForm").serialize();
$.ajax({
type: "POST",
url: "/path",
data: data,
accept: 'application/json',
}).done(function (data) {
$("#MyModal_C").modal("hide");
console.log("response: " + data);
window.location.reload();
}).fail(function (jqxhr, status, error) {
console.log("error :" + error);
}).always(function () {
console.log("complete");
});
}));

</script>

我发现,如果我更改为按钮 type="submit",则 @required = "required"可以工作,但我的 JSON POST 无法正常工作,它不会将数据发送到我的模型,并且 URL 会变得丑陋里面的数据。我该如何解决这个问题?

最佳答案

要使 HTML5 验证 ( @required ) 正常工作,需要提交表单,因此您需要 button type="submit"元素

您应该监听表单的“提交”事件,而不是捕获按钮的“单击”。

由于您不希望表单实际回发到服务器并进行页面刷新(这就是弄乱您的网址的原因),因此您需要阻止提交事件执行页面发布,因此您需要使用event.preventDefault()

所以你的事件处理看起来像这样

$("#form").on('submit', (function (event) {
event.preventDefault();

// Do your ajax stuff here

})

虽然您只是重新加载页面,但如果您只是设置表单方法来发布数据,那么数据将作为表单数据发送,而不是在 URL 中发送

<form method="POST">

那么你就不需要ajax处理

关于javascript - Bootstrap 4 使用 JSON 进行模态验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59130577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com