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?
Ah… found the solution myself, after a good nights sleep 🙂
Replacing the RadioButtonListFor with the below:
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.