Define markup for [Required] fields in a view in ASP.NET MVC 2.0

We have a model with properties decorated with [Required], which is great for validation. However, we would like to mark those required fields in the presentation with an asterisk (or some other style) to indicate that they are necessary before the user enters any data for verification.

It seems I can’t find anything built into the MVC framework to allow me to do this, and therefore wondered if anyone else allowed this and how?

Ultimately, what we are trying to prevent is the need to change the code in two places, if you later remove the [Required] property from the model property.

Many thanks

+3
source share
5 answers

You can create 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;
}
+4
source

The problem with the solution from Gregoire and Faxanadu is that "*" is always displayed, also when the field is checked using a regular check, and you use "Html.ValidationMessageFor ()".

So, if you use the html extension as follows:

@Html.EditorFor(model => model.Email)
@Html.RequiredFieldFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)

You will see a duplicate * if the field has validation errors.


I made this modified extension based on this , which also checks if the field has been checked.

private static Type[] RequiredTypes = new Type[] { typeof(CustomRequiredAttribute), typeof(RequiredAttribute) };

/// <summary>
/// Generate a &lt;span class="field-validation-error"&gt;*&lt;&lt; element.
/// 
/// See http://koenluyten.blogspot.com/2011/06/denote-required-fields-in-aspnet-mvc-3.html
/// </summary>
public static MvcHtmlString RequiredFieldFor<TModel, TValue>(this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> expression, string validationMessage = "*")
{
    // Get the metadata for the model
    var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);

    string fieldName = metadata.PropertyName;

    // Check if the field is required
    bool isRequired = metadata
        .ContainerType.GetProperty(fieldName)
        .GetCustomAttributes(false)
        .Count(m => RequiredTypes.Contains(m.GetType())) > 0;

    // Check if the field is validated
    bool isValidated = html.ViewData.ModelState[fieldName] != null;

    // If the field is required and not validated; generate span with an asterix
    if (isRequired && !isValidated)
    {
        var span = new TagBuilder("span");
        span.AddCssClass("field-validation-error");
        span.SetInnerText(validationMessage);

        return MvcHtmlString.Create(span.ToString(TagRenderMode.Normal));
    }

    return null;
}
+3
source

" " "ModelMetadata.FromLambdaExpression", , HtmlHelper. Gregoire:

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

EditorFor DisplayFor, Object.ascx.

, :

http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html

, IsRequired ModelMetadata . Inside Object.ascx:

<%=propertu.IsRequired ? "*" : ""%>

, html-. ?

+1
source

Now my question is a little old, but I'm working on an unobtrusive solution using only jquery.

My goal is to get all the inputs marked with the val-val attribute and then set its element labels with attributes for

Here is a sample jquery code:

$('[data-val-required]').each(function() { 
    var $label = $('label[for=' + this.name + ']');

    //from here we can manipulate the label element
    $label.css('font-weight', 'bold');
    $label.text($label.text() + ' *');
});
0
source

Source: https://habr.com/ru/post/1748531/


All Articles