【发布时间】:2018-01-05 15:42:54
【问题描述】:
我有以下 Jquery 验证码:
$("#formObjective").validate({
messages:
{
Statement: 'Value must be provided'
},
submitHandler: function (form) {
try {
$.post($('form#formObjective').attr('action'), $('form#formObjective').serializeArray())
.done(function (data) {
updateObjectiveGrid('table#objectiveGrid');
$('form#formObjective').closest('div').html(data);
})
.fail(function (xhr, error, text) {
alert(text);
});
}
catch (ex) {
alert('An error occurred while saving: ' + ex);
}
}
}
这是 HTML
<div id=editor>
@using (Html.BeginForm("Save", "Objective", FormMethod.Post, new { @class = "form", id = "formObjective" }))
{
<fieldset>
<legend>Add Objective</legend>
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Notes, "Notes", htmlAttributes: new { @class = "control-label" })
@Html.TextAreaFor(model => model.Notes, new { @class = "form-control" } )
</div>
<div class="form-group">
<button type="submit" id="save" name="action" class="btn btn-primary btn-default">@Html.GlyphIcon("plus") Save Objective</button>
<button type="button" id="clear" name="action" class="btn btn-warning">Clear</button>
</div>
</fieldset>
}
</div>
现在我面临两个问题。
如果我将 $('').validate({}) 放在 $(document).ready(function(){}) 它只是不起作用,即常规 提交发生。如果我把它放在外面,它就可以工作。
如果我动态替换 (相同的形式 从服务器呈现并替换现有表单),然后 validate() 只是停止工作并定期回发。
【问题讨论】:
-
您在 ajax 调用中将
<form>替换为id="formObjective",因此您处理的那个不再存在。你需要使用Event Delegation -$('#editor').on('submit', 'form', function() { ...});
标签: jquery ajax asp.net-mvc jquery-validate