我在从 MSAjax MVC 3 Razor 视图生成的表单上使用了 jQuery ajax 帖子。
在这种形式中,客户端验证在输入过程中正常工作,但是当用户生成“POST”点击“搜索”按钮时,客户端验证停止运行!
这是模型:
public class AnagraficaSearchViewModel : ViewModelBase
{
[Required]
[StringLength(2)]
public virtual string Ricerca { get; set; }
}
这是控制器:
[HttpPost]
public ActionResult Index(AnagraficaSearchViewModel model)
{
if (model.Ricerca == "12")
{
model.Status = Status.Error;
model.Message = "Errore!";
ModelState.AddModelError("", Cult.Testo(Cult.CultTextsIDs.StatusError));
}
if (Request.IsAjaxRequest()) return PartialView("SearchCriteria", model);
return View(model);
}
这是主要观点:
<div id="search-anagrafica-criteria">
@{ Html.RenderPartial("SearchCriteria", Model); }
</div>
这是 SearchCriteria 视图:
@model AnagraficaSearchViewModel
<script type="text/javascript">
function CheckRow() {
$("form").valid();
abs.message.convertErrorsToTooltips();
};
function InitSearch() {
$("#Ricerca").bind("propertychange keyup input paste", function () {
setTimeout("CheckRow();", 100);
});
CheckRow();
$("#Ricerca").focus();
}
$(function () {
$('form').submit(function (e) {
e.preventDefault();
var $form = $(this);
if (!$form.valid()) {
abs.message.convertErrorsToTooltips();
return false;
}
$.validator.unobtrusive.parse($('form')); //added
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#search-anagrafica-criteria').html(result);
InitSearch();
},
complete: function (result) {
CheckRow();
}
});
}
return false;
});
InitSearch();
});
</script>
@using (Ajax.BeginForm("Index", "Anagrafica", null, new AjaxOptions { UpdateTargetId = "search-anagrafica-criteria", HttpMethod = "POST", OnComplete = "CheckRow()" }))
{
@Html.LabelFor(el => el.Ricerca)
@Html.TextBoxFor(el => el.Ricerca)
@Html.ValidationMessageFor(el => el.Ricerca)
<button class="btn btn-primary" type="submit" style="margin-left: 10px">Search</button>
@Html.ValidationSummary(true)
}
工作了好几个小时,没有任何改变!!
感谢您的任何帮助!