【发布时间】:2018-09-30 01:54:12
【问题描述】:
当单击 jQuery 数据表中的一行时,我会打开一个模式对话框,并使用从所选行获取的数据填充它。用户可以更新一些字段并提交。我有客户端验证;像此文本这样的基本类型是必需的,或者从下拉列表中选择一些内容。
对于一个字段,我需要检查需要服务器端检查的重复值(例如重复名称)。问题是当我进行服务器端检查时,回发会关闭模式对话框。所以,对于这一部分,我按照建议使用了 ajax。
按照@Rafalon 的建议,我设法进行了 ajax 调用来验证输入。但是,当调用函数 valiadteSubmit() 时,它会进行其他验证,然后执行 ajax 调用并退出,关闭模式,即使在 .done() 中我可以看到错误被捕获。请看下面:
<div class="modal fade" id="newModal" role="dialog" aria-labelledby="editLabel" aria-hidden="true">
<div class="modal-dialog modal-lg fade in ui-draggable">
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="tbName">Name</label>
<input type="text" runat="server" id="tbName" class="form-control" clientidmode="Static" />
<span id="lblErrName" class="field-validation-error pull-left" style="display: inline"></span>
</div>
</div>
...
</div>
</div>
<div class="modal-footer">
<div id="divNewButtons" style="text-align: center;">
<button id="btnCancel" class="btn btn-info2" data-dismiss="modal" aria-hidden="true" aria-label="Cancel">Cancel</button>
<button id="btnSubmit" class="btn btn-primary" aria-hidden="true" aria-label="Submit">Submit</button>
</div>
</div>
</div>
</div>
$(document).on("click", "#btnSubmit", function (event) {
var isValid = validateSubmit();
if (isValid) {
// do whatever
}
else
return false;
});
function validateSubmit() {debugger
var isValid = true;
var name = $("#tbName").val();
var districtID = $("#ddlDistrict").val();
var nameErr = false;
// this gets executed after other validations following it
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: '/services/mpoo.asmx/NameExists',
cache: false,
data: JSON.stringify({ "Name": name, "DistrictID": districtID }),
}).done(function (data) {debugger
nameErr = JSON.parse(data.d); // this is "true" or "false"
if (nameErr == 'true') {
// This error never gets displayed because modal closes
$("#lblErrName").text("Duplicate Name within selected District");
$("#lblErrName").show();
isValid = false; // I tried "return false;"
}
});
if (name == '') {
$("#lblErrName").text("Name is required");
$("#lblErrName").show();
isValid = false; // also tried "return false;"
}
... // other validations here
return isValid;
}
【问题讨论】:
-
您可以使用 javascript
getJson调用服务器操作,该操作将在不提交表单的情况下检查重复项 -
您正在使用 Web 表单?
-
是的,它是一个 asp.net 网络表单。
-
@Rafalon 你能给我看个sn-p吗?
-
根据 getJson() 建议更新了问题。我只是不清楚“数据”的重要性以及我的方法是否正确。
标签: javascript c# jquery asp.net webforms