在加载表单时未选中单选按钮?

时间:2016-09-22 15:21:37

标签: javascript c# asp.net-mvc

我在这里遇到一个小问题,每次运行应用程序时,总会检查第一个单选按钮,我想要检查单选按钮。我该怎么做呢?

 <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>

这是我的模特

[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
        }

这是我的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
            }
        });

最后我有一个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;
        }

    }

}

1 个答案:

答案 0 :(得分:1)

要不选择任何单选按钮,请创建属性nullable

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

如果CCommmunication的初始值为null,则不会选择任何单选按钮。

但是不清楚你在扩展方法中尝试使用所有(不必要的)代码做什么,特别是为什么要创建IList<SelectListItem>(用于生成<select>标记)。你的助手可以简单地

 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());
    }
}

使用以下扩展方法

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();
    }
}

与应用于[Description]值的enum属性相关联,而不是[Display]属性(但您可以轻松修改该属性)