Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6663943
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T02:33:18+00:00 2026-05-26T02:33:18+00:00

I have a class where I have used data annotations: [Required(ErrorMessage = You must

  • 0

I have a class where I have used data annotations:

[Required(ErrorMessage = "You must indicate which sex you are.)]
public string Sex { get; set; }

I have also created a custom HtmlHelper called RadioButtonListFor, which I can call like this:

@Html.RadioButtonListFor(m => m.Sex, "SexList")

My SexList is defined like this:

IList<string> SexList = new List() { "Male", "Female"};

And below is the RadioButtonListFor extension (not totally finished yet):

public static class RadioButtonListForExtentions
{
    public static IHtmlString RadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string list)
    {
        string prefix = ExpressionHelper.GetExpressionText(expression);
        if (string.IsNullOrEmpty(prefix))
            prefix = "empty";
        int index = 0;

        var items = helper.ViewData.Eval(list) as IEnumerable;
        if (items == null)
            throw new NullReferenceException("Cannot find " + list + "in view data");

        string txt = string.Empty;
        foreach (var item in items)
        {
            string id = string.Format("{0}_{1}", prefix, index++).Replace('.','_');
            TagBuilder tag = new TagBuilder("input"); 
            tag.MergeAttribute("type", "radio");
            tag.MergeAttribute("name", prefix);
            tag.MergeAttribute("id", id);
            tag.MergeAttribute("data-val-required", "Missing");
            tag.MergeAttribute("data-val", "true");

            txt += tag.ToString(TagRenderMode.Normal);
            txt += item;
        }

        return helper.Raw(txt);
    }
}

My problem is this: Right now I have hardcoded the word “Missing” in the attribute “data-val-required”. How do I get the text I stated in my data annotations?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T02:33:19+00:00Added an answer on May 26, 2026 at 2:33 am

    Ah… found the solution myself, after a good nights sleep 🙂

    Replacing the RadioButtonListFor with the below:

    public static IHtmlString RadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string list)
        {
            string prefix = ExpressionHelper.GetExpressionText(expression);
            if (string.IsNullOrEmpty(prefix))
                prefix = "empty";
            int index = 0;
    
            var items = helper.ViewData.Eval(list) as IEnumerable;
            if (items == null)
                throw new NullReferenceException("Cannot find " + list + "in view data");
    
            var validationAttributes = helper.GetUnobtrusiveValidationAttributes(prefix);
    
            string txt = string.Empty;
            foreach (var item in items)
            {
                string id = string.Format("{0}_{1}", prefix, index++).Replace('.','_');
                TagBuilder tag = new TagBuilder("input"); 
                tag.MergeAttribute("type", "radio");
                tag.MergeAttribute("name", prefix);
                tag.MergeAttribute("id", id);
                foreach (KeyValuePair<string, object> pair in validationAttributes)
                {
                    tag.MergeAttribute(pair.Key, pair.Value.ToString());
                }
                txt += tag.ToString(TagRenderMode.Normal);
                txt += item;
            }
    
            return helper.Raw(txt);
        }
    

    Basically I have added “validationAttributes” which apparently is a dictionary of my validation items. And looping through these and adding them makes it work like a charm!

    Edited October 13th 2011:

    Ended up with the below solution. Instead of just getting a list of strings, I decided to send in a Dictionary where the key is the radiobutton value and the value of the dictionary is the radiobutton text.

    public static IHtmlString RadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string list)
        {
            string prefix = ExpressionHelper.GetExpressionText(expression);
            if (string.IsNullOrEmpty(prefix))
                prefix = "empty";
    
            // find existing value - if any
            string value = helper.ViewData.Eval(prefix) as string;
    
            var validationAttributes = helper.GetUnobtrusiveValidationAttributes(prefix);
            string txt = string.Empty;
    
            // create hidden field for error msg/value
            TagBuilder tagHidden = new TagBuilder("input");
            tagHidden.MergeAttribute("type", "hidden");
            tagHidden.MergeAttribute("name", prefix);
            tagHidden.MergeAttribute("value", value);
            tagHidden.MergeAttribute("id", prefix.Replace('.', '_'));
            foreach (KeyValuePair<string, object> pair in validationAttributes)
            {
                tagHidden.MergeAttribute(pair.Key, pair.Value.ToString());
            }
            txt += tagHidden.ToString(TagRenderMode.Normal);
    
            // prepare to loop through items
            int index = 0;
            var items = helper.ViewData.Eval(list) as IDictionary<string, string>;
            if (items == null)
                throw new NullReferenceException("Cannot find " + list + "in view data");
    
            // create a radiobutton for each item. "Items" is a dictionary where the key contains the radiobutton value and the value contains the Radiobutton text/label
            foreach (var item in items)
            {
                string id = string.Format("{0}_{1}", prefix, index++).Replace('.','_');
                TagBuilder tag = new TagBuilder("input"); 
                tag.MergeAttribute("type", "radio");
                tag.MergeAttribute("name", prefix);
                tag.MergeAttribute("id", id);
                tag.MergeAttribute("value", item.Key);
                if (item.Key == value)
                    tag.MergeAttribute("checked", "true");
                tag.MergeAttribute("onclick", "javascript:" + tagHidden.Attributes["id"] + ".value='" + item.Key + "'");
                txt += tag.ToString(TagRenderMode.Normal);
                txt += item.Value;
            }
    
            return helper.Raw(txt);
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider I have a these two properties: public class Test { [Required(ErrorMessage = Please
Let's say I have a class that has a member called data which is
I have a subclass of NSManagedObject Class used with Core Data in iPhone. However,
I have a class which displays waveform data of audiofiles in a QWidget (see
Imagine I have a class used to represent some trivial numerical data, like a
I have the following class : import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent;
I have a project in which I have a database model class provided along
Where I can download sample database which can be used for data warehouse creation?
I have class A: public class ClassA<T> Class B derives from A: public class
We have a service that runs methods used for data import/export at specified intervals.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.