MVC 3部分视图验证问题
我正在尝试使用 DataAnnotations
验证部分视图中的表单。
问题是当我检查表单在 JavaScript 中是否有效时,它总是返回 true,即使表单不符合要求。
这是始终返回 true 的行: var valid = $("#create-language-form").valid();
在我的模型中,我得到了这个
[Required(ErrorMessage="Please enter a name")]
public string Name { get; set; }
:我的视图我得到了这个:
@using(Html.BeginForm(null, null, FormMethod.Post, new { id = "create-language-form" }))
{
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
}
在我的javascript中我得到了这个:
$("#create-language-dialog").dialog({
modal: true,
open: function (event, ui) {
$('#create-language-dialog').load("/Languages/CreatePartial", { id: objectid });
},
buttons: {
"Save": function () {
var valid = $("#create-language-form").valid();
if (valid) {
//do stuff
}
}
}
});
可能出了什么问题?为了使 MVC 验证在部分视图中工作,我错过了什么?
I'm trying to validate a form in a Partal View using the DataAnnotations
.
The problem is when I check if the form is valid in the javascript, it always returns true, even if the form doesn't meet the requirements.
This is the line who always returns true: var valid = $("#create-language-form").valid();
In my model I got this:
[Required(ErrorMessage="Please enter a name")]
public string Name { get; set; }
In my view I got this:
@using(Html.BeginForm(null, null, FormMethod.Post, new { id = "create-language-form" }))
{
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
}
In my javascript I got this:
$("#create-language-dialog").dialog({
modal: true,
open: function (event, ui) {
$('#create-language-dialog').load("/Languages/CreatePartial", { id: objectid });
},
buttons: {
"Save": function () {
var valid = $("#create-language-form").valid();
if (valid) {
//do stuff
}
}
}
});
What might be wrong? Anything I miss to make the MVC validation work in a partial view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这将验证表单并返回 true 或 false。
This will validate the form and return true or false.
我遇到了类似的问题,我编写了自己的函数,如下所示。
这将检查与 ValidationMessageFor 相对应的错误元素。我的页面有多个表单,我希望它仅适用于表单上的几个字段,因此我在
data-valmsg-for
上添加了 if 条件。如果您有一个表单并想检查是否有任何字段错误,那么您可以按如下方式查看I had similar problem and I wrote my own function as below
This will check for elements corresponding to
ValidationMessageFor
which are in error. My page had multiple forms and I wanted this to only work for few fields on a form so I added the if condition ondata-valmsg-for
. If you have got a single form and want to check if any field is in error then you can have it as below