我有一个具有 RemoteValidation 属性的模型。
当我输入数据库中已存在的“测试”并单击“确定”按钮之外的区域时,我会看到红色:“测试已存在”。到目前为止,一切都很好。当我单击“确定”按钮时,将完成我要求的“创建”操作
ModelState.IsValid 始终为 true ???
因此,数据被输入到数据库中,并且我收到重复异常...
我知道这之前在我的网站上有效,我只是更改了一些内容,而 subversion 则没有
激活啊啊啊...
我做错了什么?
[HttpPost]
public ActionResult Create(Release release)
{
if (ModelState.IsValid)
{
_releaseDataProvider.AddRelease(release);
return Json(new { success = true });
}
return PartialView(release);
}
public JsonResult ReleaseExists(string Name)
{
bool releaseExists = _releaseDataProvider.ReleaseExists(Name);
if (!releaseExists)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
else
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
$.ajaxSetup({ cache: false });
$(document).ready(function () {
$('#CreateRelease').click(function (event) { loadDialog(this, event, createRelease); });
});
function loadDialog(link, e, ajaxRequest) {
e.preventDefault();
var $title = link.innerHTML;
var $contenturl = $(link).attr('href');
var $dialog = $('<div></div>');
var $height = $(link).attr('data-dialog-height');
var $width = $(link).attr('data-dialog-width');
$dialog.load($contenturl).dialog({
title: $title,
autoOpen: true,
modal: true,
show: 'fade',
hide: 'fade',
width: $width,
height: $height,
buttons: {
"OK": function () {
ajaxRequest($(this), $('form', this));
},
"Cancel": function () {
$dialog.dialog("close");
}
}
});
}
function createRelease(dlg, form) {
$.ajax({
url: $(form).attr('action'),
type: 'POST',
data: form.serialize(),
success: function (response) {
if (response.success) {
dlg.dialog("close");
// Update UI
}
else {
// Reload the dialog with the form to show model/validation errors
dlg.html(response);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + '-' + XMLHttpRequest.responseText);
}
});
}
最佳答案
ModelState.IsValid which is always true ???
这是正常的,仅当您通过 AJAX 调用 Controller 操作时才会应用远程验证规则。当表单正常提交时,不会调用相同的操作。因此,您可以在 POST 操作中调用相应的验证方法:
[HttpPost]
public ActionResult Create(Release release)
{
if (ModelState.IsValid && !_releaseDataProvider.ReleaseExists(release.Name))
{
_releaseDataProvider.AddRelease(release);
return Json(new { success = true });
}
return PartialView(release);
}
关于asp.net-mvc - 远程验证适用于文本框失去焦点,但 ModelState.IsValid 始终为 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10822825/