Donate

Set An Html.RadioButtonFor() Helper As Default Checked In ASP.NET MVC

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! :-)

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input