C# ASPNET MVC - 如何在 jquery/ajax 回发中使用 ModelState.IsValid?
据我所知, ModelState.IsValid 仅由 MVC 框架在完整回发时计算,是这样吗?
我有一个像这样的 jquery 回发:
var url = "/path/to/controller/myaction";
var id = $("#Id").val();
var somedata = $("#somedata").val(); // repeated for every textbox
$.post(url, { id: id, somedata: somedata },
function (data) {
// etc
});
控制器操作看起来像:
public JsonResult MyAction(MyModel modelInstance)
{
if (ModelState.IsValid)
{
// ... ModelState.IsValid is always true, even when there is invalid data
}
}
但这似乎没有触发 ModelState.IsValid。例如,如果某些数据的长度为 5 个字符,但 DataAnnotation 表示 [StringLength(3)] - 在这种情况下 ModelStae.IsValid 仍然为 true,因为它尚未被触发。
在制作 jquery/ajax 帖子而不是完整帖子时,我需要做一些特别的事情吗?
谢谢!
From what I've seen ModelState.IsValid is only calculated by the MVC frame work on a full postback, is that true?
I have a jquery postback like so:
var url = "/path/to/controller/myaction";
var id = $("#Id").val();
var somedata = $("#somedata").val(); // repeated for every textbox
$.post(url, { id: id, somedata: somedata },
function (data) {
// etc
});
And the controller action looks like:
public JsonResult MyAction(MyModel modelInstance)
{
if (ModelState.IsValid)
{
// ... ModelState.IsValid is always true, even when there is invalid data
}
}
But this does not seem to trigger ModelState.IsValid. For example if somedata is 5 characters long, but the DataAnnotation says [StringLength(3)] - in this case ModelStae.IsValid is still true, because it hasn't been triggered.
Is there something special I need to do when making a jquery/ajax post instead of a full post?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,没有什么特别要做的。你的发帖逻辑可能有问题。不要手动设置发布的值,而是尝试使用 jQuery 表单插件。它使 ajax 发布变得更容易,并有助于消除奇怪的错误。
我刚刚准备了简单的例子,它工作得很好(它使用了 jQuery 形式)(编辑:$.post('/Login/Test3', { AAA: $('#AAA').val() });< /strong> 也工作得很好):
控制器:
视图:
No, there is nothing special to do. There is propably something wrong with your posting logic. Instead of setting posted values by hand, try using jQuery Form Plugin. it makes ajax posting easier and helps to get rid of weird errors.
I just prepared simple example and it worked fine (it used jQuery form) (EDIT: $.post('/Login/Test3', { AAA: $('#AAA').val() }); worked fine too):
Controller:
View: