gpt4 book ai didi

javascript - 使单选按钮在加载表单时不被选中?

转载 作者:行者123 更新时间:2023-12-03 06:03:38 26 4
gpt4 key购买 nike

我这里有一个小问题,每次运行应用程序时,第一个单选按钮总是被选中,我想让单选按钮被选中。我该怎么做呢?

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

}

}

最佳答案

要不选择任何单选按钮,请将属性设为 nullable

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

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

但不清楚您试图如何处理扩展方法中的所有(不必要的)代码,特别是为什么您要创建 IList<SelectListItem> (用于生成<select>标签)。您的 helper 可以是

 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]属性(但您可以轻松修改它)

关于javascript - 使单选按钮在加载表单时不被选中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39642976/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com