Tuesday, March 21, 2017

Set an Html.RadioButtonFor() helper as default Checked

Good day!
Given that you have to set a radio button as default checked in razor view, a code to do that is presented below using conditional ternary operator. However, there is an issue with the code shown below. Even if you set the checked property with empty string, it will still render as checked during run-time.
@foreach (var answer in item.Answers)
{
 <p>
  @Html.RadioButtonFor(m => answer.ID, true,
     new
     {
      @disabled = "true",
      @Name = item.ID,
      @checked = (answer.IsCorrect) ? "checked" : ""
     })@answer.AnswerText
 </p>
}           
To ignore that issue, there are several ways to fix that. First one is to use if statement in the view itself.
@foreach (var answer in item.Answers)
{
 <p>
  @if (answer.IsCorrectAnswer)
  {
   @Html.RadioButtonFor(m => answer.ID, true,
     new
     {
      @disabled = "true",
      @Name = item.ID,
      @checked = "true"
     })@answer.AnswerText

  }
  else
  {

   @Html.RadioButtonFor(m => answer.ID, false,
     new
     {
      @disabled = "true",
      @Name = item.ID,
     })@answer.AnswerText
  }
 </p>
}
And another one is to create a custom RadioButton helper.
public static MvcHtmlString RadioButtonFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, 
 Expression<Func<TModel, TValue>> expression, object value, object htmlAttributes, bool checkedState)
{
 var htmlAttributeDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

 TagBuilder tagbuilder = new TagBuilder("input");
 tagbuilder.Attributes.Add("value", value.ToString());
 tagbuilder.Attributes.Add("type", "radio");
 tagbuilder.Attributes.Add("id", ExpressionHelper.GetExpressionText(expression));

 if (checkedState)
 {
  tagbuilder.Attributes.Add("checked", "checked");
 }

 foreach (var item in htmlAttributeDictionary)
 {
  tagbuilder.Attributes.Add(item.Key, item.Value.ToString());
 }

 return MvcHtmlString.Create(tagbuilder.ToString(TagRenderMode.Normal));
}
Usage of custom HtmlHelper
@Html.RadioButtonFor(m => answer.ID, (answer.IsCorrectAnswer) ? true : false, new
{
 @disabled = "true",
 @Name = String.Format("Question_{0}", item.ID),
}, answer.IsCorrectAnswer)@answer.Text

Cheers! :-)

0 comments:

Post a Comment