user6838820
user6838820

Reputation:

Make radio button not checked on load of form?

I have a slight problem here that each time I run the application the first radio button is always checked, I want to make nun of the radio buttons checked. How do I do this?

 <div class="col-md-12">
     <!--<i class="fa fa-child" aria-hidden="true"></i>-->
     @Html.LabelFor(model => model.CCommmunication, "Choose your preferred way of communication", new { @style = "", @class = "", id = "" })
     <span style="color: red;">*</span>
     @*@Html.DropDownListFor(model => model.Profession, new SelectList(Model.Professions, "Id", "Name"), new { placeholder = "", @style = "", @class = "form-control", id = "Profession" })*@
     @Html.EnumRadioButtonFor(model => model.CCommmunication, false,false,"communicationCB") <!--first 2 paramerters are false false communicationCB is the class-->
     @Html.ValidationMessageFor(model => model.CCommmunication)
 </div>

this is my Model

[Required(ErrorMessage = "Please select preferred way of communication option")]
        public Commmunication CCommmunication
        { get; set; }

        public enum Commmunication
        {
            [Display(Name = "Email", Order = 0)]
            Email,

            [Display(Name = "Mobile telephone", Order = 1)]
            TelephoneNo,

            [Display(Name = "Alternative telephone", Order = 2)]
            TelephoneNoAlternative
        }

This is my JavaScript

<script>

        var checkedVal = $('.communicationCB input[name=CCommmunication]:checked').val(); //Added a variable to check the value
        if (checkedVal == "TelephoneNo") { //if checked valuie
            $('.confirmmobtelno').show(); //show this text box
        } else {
            $('.confirmmobtelno').hide(); //hide textbox
        };

        if (checkedVal == "TelephoneNoAlternative") {  //if checked valuie == to TelephoneNoalternative
            $('.confirmalttelno').show(); //show confirm alt tel no text box
        } else {
            $('.confirmalttelno').hide(); //else hide it
        };



        $('.communicationCB input[name=CCommmunication]').click(function () { //.communication class passed input name == model public communication
            if ($(this).val() == "TelephoneNo") { //if value TelephoneNo selected in model
                $('.confirmmobtelno').show(); //show this text box
            } else {
                $('.confirmmobtelno').hide(); //hide textbox
            }

            if ($(this).val() == "TelephoneNoAlternative") {  //if value == to TelephoneNoalternative
                $('.confirmalttelno').show(); //show confirm alt tel no text box
            } else {
                $('.confirmalttelno').hide(); //else hide it
            }
        });

Finally I have a enumRadioButton.cs

  public static class HtmlHelper
    {
        public static MvcHtmlString EnumRadioButtonFor<TModel, TProperty>(
                this HtmlHelper<TModel> htmlHelper,
                Expression<Func<TModel, TProperty>> expression,
                bool includeNoneOption = true,
                bool isDisabled = false,
                string cssClass = null
            ) where TModel : class
        {
            var memberExpression = expression.Body as MemberExpression;
            if (memberExpression == null)
                throw new InvalidOperationException("Expression must be a member expression");

            var name = ExpressionHelper.GetExpressionText(expression);
            var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
            ModelState currentValueInModelState;
            var couldGetValueFromModelState = htmlHelper.ViewData.ModelState.TryGetValue(fullName, out currentValueInModelState);
            object selectedValue = null;
            if (couldGetValueFromModelState && htmlHelper.ViewData.Model != null)
            {
                selectedValue = expression.Compile()(htmlHelper.ViewData.Model);
            }

            var enumNames = GetSelectItemsForEnum(typeof(TProperty), selectedValue).Where(n => !string.IsNullOrEmpty(n.Value)).ToList();


            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var sb = new StringBuilder();
            sb.AppendFormat(
                "<ul class=\"radio-button-list{0}\">",
                string.IsNullOrEmpty(cssClass) ? string.Empty : " " + cssClass);
            foreach (var enumName in enumNames)
            {
                var id = string.Format(
                    "{0}_{1}_{2}",
                    htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
                    metaData.PropertyName,
                    enumName.Value
                    );

                if (id.StartsWith("-"))
                    id = id.Remove(0, 1);

                var value = enumName.Value;

                sb.AppendFormat(
                      //"<li>{2} <label for=\"{0}\">{1}</label></li>", //Originol puts data in a list 
                      "{2} <label for=\"{0}\">{1}</label>",
                    id,
                    HttpUtility.HtmlEncode(enumName.Text),
                    isDisabled
                        ? htmlHelper.RadioButtonFor(expression, value, new { id, disabled = "disabled" }).ToHtmlString()
                        : htmlHelper.RadioButtonFor(expression, value, new { id }).ToHtmlString()
                    );
            }
            sb.Append("</ul>");
            return MvcHtmlString.Create(sb.ToString());
        }
        public static IList<SelectListItem> GetSelectItemsForEnum(Type enumType, object selectedValue)
        {
            var selectItems = new List<SelectListItem>();

            if (enumType.IsGenericType &&
                enumType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                enumType = enumType.GetGenericArguments()[0];
                selectItems.Add(new SelectListItem { Value = string.Empty, Text = string.Empty });
            }

            var selectedValueName = selectedValue != null ? selectedValue.ToString() : null;
            var enumEntryNames = Enum.GetNames(enumType);
            var entries = enumEntryNames
                .Select(n => new
                {
                    Name = n,
                    DisplayAttribute = enumType
                        .GetField(n)
                        .GetCustomAttributes(typeof(DisplayAttribute), false)
                        .OfType<DisplayAttribute>()
                        .SingleOrDefault() ?? new DisplayAttribute()
                })
                .Select(e => new
                {
                    Value = e.Name,
                    DisplayName = e.DisplayAttribute.Name ?? e.Name,
                    Order = e.DisplayAttribute.GetOrder() ?? 50
                })
                .OrderBy(e => e.Order)
                .ThenBy(e => e.DisplayName)
                .Select(e => new SelectListItem
                {
                    Value = e.Value,
                    Text = e.DisplayName,
                    Selected = e.Value == selectedValueName
                });

            selectItems.AddRange(entries);

            return selectItems;
        }

    }

}

Upvotes: 0

Views: 825

Answers (1)

user3559349
user3559349

Reputation:

To have none of the radio buttons selected, you make the property nullable

[Required(ErrorMessage = "Please select preferred way of communication option")]
public Commmunication? CCommmunication { get; set; }

If CCommmunication has an initial value of null, then no radio buttons will be selected.

But its unclear what you trying to do with all that (unnecessary) code in you extension method, in particular why you are creating IList<SelectListItem> (which is for generating a <select> tag). Your helper can simply be

 public static class RadioButtonHelper
 {
    public static MvcHtmlString EnumRadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
    {
        ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        string name = ExpressionHelper.GetExpressionText(expression);
        Type type = Nullable.GetUnderlyingType(metaData.ModelType);
        if (type == null || !type.IsEnum)
        {
            throw new ArgumentException(string.Format("The property {0} is not an enum", name));
        }
        StringBuilder html = new StringBuilder();
        foreach (Enum item in Enum.GetValues(type))
        {
            string id = string.Format("{0}_{1}", metaData.PropertyName, item);
            StringBuilder innerHtml = new StringBuilder();
            innerHtml.Append(helper.RadioButtonFor(expression, item, new { id = id }));
            innerHtml.Append(helper.Label(id, item.ToDescription()));
            TagBuilder div = new TagBuilder("div");
            div.AddCssClass("radiobutton");
            div.InnerHtml = innerHtml.ToString();
            html.Append(div.ToString());
        }
        TagBuilder container = new TagBuilder("div");
        container.AddCssClass("radiobutton-container");
        container.InnerHtml = html.ToString();
        return MvcHtmlString.Create(container.ToString());
    }
}

which uses the following extension method

public static class EnumExtensions
{
    public static string ToDescription(this Enum value)
    {
        if (value == null)
        {
            return null;
        }
        FieldInfo field = value.GetType().GetField(value.ToString());
        DescriptionAttribute[] attributes = (DescriptionAttribute[])field
            .GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attributes.Length > 0)
        {
            return attributes[0].Description;
        }
        return value.ToString();
    }
}

in association with the [Description] attribute applied to your enum values rather that the [Display] attribute (but you can easily modify that)

Upvotes: 1

Related Questions