gpt4 book ai didi

c# - ASP.NET MVC 3 客户端验证

转载 作者:太空宇宙 更新时间:2023-11-03 11:41:04 25 4
gpt4 key购买 nike

我有以下 View 模型:

public class ViewModel
{
[Display(Name = "firstname", ResourceType = typeof(Views.Validation))]
public string firstname { get; set; }

[Required(ErrorMessageResourceName="required", ErrorMessageResourceType = typeof(Views.Validation))]
[Display(Name="lastname", ResourceType = typeof(Views.Validation))]
public string lastname { get; set; }

...
}

和我的 HTML View :

    ...
<div class="row valid showMsg">
<div class="itemWrap clearfix">
<label>@Html.LabelFor(model => model.firstname)<span class="iconReq">&nbsp;</span>:</label>
@Html.EditorFor(model => model.firstname)
</div>
<div class="info">
<p class="errorMsg">@Html.ValidationMessageFor(model => model.firstname)</p>
<p class="infoMsg">info message here</p>
<p class="focusMsg">text on active</p>
</div>
</div>
...

如果您在我的 HTML View 中注意到我有一个 <div class="row valid showMsg">带有一个类“showMsg”,它控制消息在我的 <div class="info"> 中的显示.

现在,为了服务器验证,我编写了一个自定义 HTML 帮助器,它在无效时将那个类“showMsg”添加到 div,如下所示:

 public static MvcHtmlString ValidationRowFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)
{
MvcHtmlString normal = html.ValidationMessageFor(expression);

if (normal != null)
{
return MvcHtmlString.Create("errorOn");
}

return null;
}

然后像这样使用它:

<div class="row valid @Html.ValidationRowFor(model => model.firstname)">

我想对客户端验证做同样的事情。这样它会在错误时自动将“showMsg”类添加到父类。我该怎么做?

谢谢。

编辑:好的,这适用于常规 HTML 但不适用于 MVC3 ??

$(function(){
var validator = $(".form").validate({
highlight: function(element) {
$(element).parents().closest('div.row').addClass('errorOn');
},

unhighlight: function(element) {
$(element).parents().closest('div.row').removeClass('errorOn');
}
});
});

最佳答案

也许行中的某些内容应该可以完成这项工作:

$(function () {
$('form').submit(function () {
$(this).validate().invalidElements().each(function () {
$(this).closest('div.row.valid').addClass('showMsg');
});
});
});

关于c# - ASP.NET MVC 3 客户端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4790975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com