定义在ASP.NET MVC 2.0中查看[必填]字段标记 [英] Define markup for [Required] fields in View in ASP.NET MVC 2.0

查看:433
本文介绍了定义在ASP.NET MVC 2.0中查看[必填]字段标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有性能饰[必填]这对于验证的伟大工程的典范。然而,我们想要做的是标志着鉴于这些必填字段以星号(或其他方式)来表示用户输入进行验证任何数据之前,他们是必须的。

We have a model with properties decorated with [Required] which works great for validation. However, what we'd like to do is mark those required fields in the view with an asterisk (or some other style) to denote they are required before the user enters any data for validation.

我似乎没有能够找到内置MVC框架什么让我做到这一点,因此不知道是否有人已经解决了这个问题以及如何?

I don't seem to be able to find anything built into the MVC framework to allow me to do this and therefore wondered if anyone else had already solved this and how?

最终我们正在试图prevent是改变code在两个地方,如果我们随后从一个模型属性中删除[必填]的需求。

Ultimately what we're trying to prevent is the need to change code in two places if we subsequently remove a [Required] from a model property.

非常感谢

推荐答案

您可以建立自己的HtmlHelper扩展这样的:

You can build your own HtmlHelper extension for this:

public static string RequiredMarkFor<TModel, TValue>(this HtmlHelper html, Expression<Func<TModel, TValue>> expression)
{
    if(ModelMetadata.FromLambdaExpression(expression, html.ViewData).IsRequired)
         return "*";
    else
         return string.Empty;
}

这篇关于定义在ASP.NET MVC 2.0中查看[必填]字段标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆