DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • Motivations for Creating Filter and Merge Plugins for Apache JMeter With Use Cases
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel

Trending

  • Optimizing Serverless Computing with AWS Lambda Layers and CloudFormation
  • When Airflow Tasks Get Stuck in Queued: A Real-World Debugging Story
  • How to Introduce a New API Quickly Using Micronaut
  • Is Big Data Dying?
  1. DZone
  2. Coding
  3. Frameworks
  4. ASP.NET MVC – How To Show Asterisk By Required Labels

ASP.NET MVC – How To Show Asterisk By Required Labels

By 
Gunnar Peipman user avatar
Gunnar Peipman
·
Jun. 18, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
20.3K Views

Join the DZone community and get the full member experience.

Join For Free

Usually we have some required fields on our forms and it would be nice if ASP.NET MVC views can detect those fields automatically and display nice red asterisk after field label. As this functionality is not built in I built my own solution based on data annotations. In this posting I will show you how to show red asterisk after label of required fields.

Here are the main information sources I used when working out my own solution:

  • How can I modify LabelFor to display an asterisk on required fields? (stackoverflow)
  • ASP.NET MVC – Display visual hints for the required fields in your model (Radu Enucă)

Although my code was first written for completely different situation I needed it later and I modified it to work with models that use data annotations. If data member of model has Required attribute set then asterisk is rendered after field. If Required attribute is missing then there will be no asterisk.

Here’s my code. You can take just LabelForRequired() methods and paste them to your own HTML extension class.

public static class HtmlExtensions
{
    [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
    public static MvcHtmlString LabelForRequired<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText = "")
    {
        return LabelHelper(html,
            ModelMetadata.FromLambdaExpression(expression, html.ViewData),
            ExpressionHelper.GetExpressionText(expression), labelText);
    }
 
    private static MvcHtmlString LabelHelper(HtmlHelper html,
       ModelMetadata metadata, string htmlFieldName, string labelText)
    {
        if (string.IsNullOrEmpty(labelText))
        {
            labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
        }
 
        if (string.IsNullOrEmpty(labelText))
        {
            return MvcHtmlString.Empty;
        }
 
        bool isRequired = false;
 
        if (metadata.ContainerType != null)
        {
            isRequired = metadata.ContainerType.GetProperty(metadata.PropertyName)
                            .GetCustomAttributes(typeof(RequiredAttribute), false)
                            .Length == 1;
        }
 
        TagBuilder tag = new TagBuilder("label");
        tag.Attributes.Add(
            "for",
            TagBuilder.CreateSanitizedId(
                html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)
            )
        );
 
        if (isRequired)
            tag.Attributes.Add("class", "label-required");
 
        tag.SetInnerText(labelText);
 
        var output = tag.ToString(TagRenderMode.Normal);
 
 
        if (isRequired)
        {
            var asteriskTag = new TagBuilder("span");
            asteriskTag.Attributes.Add("class", "required");
            asteriskTag.SetInnerText("*");
            output += asteriskTag.ToString(TagRenderMode.Normal);
        }
        return MvcHtmlString.Create(output);
    }
}

And here’s how to use LabelForRequired extension method in your view:

<div class="field">
    @Html.LabelForRequired(m => m.Name)
    @Html.TextBoxFor(m => m.Name)
    @Html.ValidationMessageFor(m => m.Name)
</div> 

After playing with CSS style called .required my example form looks like this:

LabelForRequired in action

These red asterisks are not part of original view mark-up. LabelForRequired method detected that these properties have Required attribute set and rendered out asterisks after field names.

NB! By default asterisks are not red. You have to define CSS class called “required” to modify how asterisk looks like and how it is positioned.

ASP.NET MVC ASP.NET Asterisk (PBX) Label

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • Motivations for Creating Filter and Merge Plugins for Apache JMeter With Use Cases
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!