在 MVC 2 中使用 DataAnnotations 时,是否有一种显示所需字段指示符的好方法?

发布于 2024-08-29 16:54:40 字数 168 浏览 9 评论 0原文

我已经在所有模型上使用 DataAnnotations 进行了验证,但我想在页面加载时显示必填字段的指示器。由于我已经集中了所有验证,因此我不想在视图中硬编码指示器。在加载时调用验证将显示验证摘要。有没有人找到一种好方法让模型确定需要什么,但在渲染视图时检查它,类似于 Html.ValidationMessageFor?

I've got validation working with DataAnnotations on all my models, but I'd like to display an indicator for required fields on page load. Since I've got all my validation centralized, I'd rather not hard-code indicators in the View. Calling validation on load would show the validation summary. Has anyone found a good way of letting the model determine what's required, but checking it upon rendering the view, similar to Html.ValidationMessageFor?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

几味少女 2024-09-05 16:54:40

这超出了我的想象,但它应该可以帮助您开始:

public static MvcHtmlString IsRequiredTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
   if (expression.IsRequired())
      return MvcHtmlString.Create(string.Format("{0} [REQUIRED]", helper.TextBoxFor(expression)));

   return helper.TextBoxFor(expression);
}

public static bool IsRequired<T, V>(this Expression<Func<T, V>> expression)
{
   var memberExpression = expression.Body as MemberExpression;
   if (memberExpression == null)
      throw new InvalidOperationException("Expression must be a member expression");

   return memberExpression.Member.GetAttribute<RequiredAttribute>() != null;
}

public static T GetAttribute<T>(this ICustomAttributeProvider provider) where T : Attribute
{
   var attributes = provider.GetCustomAttributes(typeof(T), true);
   return attributes.Length > 0 ? attributes[0] as T : null;
}

This is off the top of my head, but it should get you started:

public static MvcHtmlString IsRequiredTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
   if (expression.IsRequired())
      return MvcHtmlString.Create(string.Format("{0} [REQUIRED]", helper.TextBoxFor(expression)));

   return helper.TextBoxFor(expression);
}

public static bool IsRequired<T, V>(this Expression<Func<T, V>> expression)
{
   var memberExpression = expression.Body as MemberExpression;
   if (memberExpression == null)
      throw new InvalidOperationException("Expression must be a member expression");

   return memberExpression.Member.GetAttribute<RequiredAttribute>() != null;
}

public static T GetAttribute<T>(this ICustomAttributeProvider provider) where T : Attribute
{
   var attributes = provider.GetCustomAttributes(typeof(T), true);
   return attributes.Length > 0 ? attributes[0] as T : null;
}
晚雾 2024-09-05 16:54:40

您可以添加一个渲染方法,该方法使用反射来检查字段上的必需属性。

You could add a render method that uses reflection to check for the Required attribute on the field.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文