在MVC Razor项目中,我使用RadioButtonList来生成我的单选按钮。下面是我的代码示例:
@Html.RadioButtonList(n => n.HouseType)由于某种原因,我的单选按钮列表会得到一个预选的值。第一个复选框总是被选中,这使我的UI有点混乱。
我怎样才能用好的方式禁用它呢?
一种方法是使用Jquery循环整个页面,并取消选中每个框。但这并不是一件很好的工作。
编辑:这里有关于HouseType的更多信息,这是一个自定义枚举。
public enum HouseType
{
House,
Apartment,
Garage
};它是通过使用这一行来调用的。
public HouseType HouseType { get; set; }发布于 2012-10-16 07:34:57
您可以将HouseType属性设置为视图模型上的可空类型。例如,如果它是枚举类型:
public HouseTypes? HouseType { get; set; }或者如果它是一个整数:
public int? HouseType { get; set; }更新:
您似乎正在使用following helper。此助手不支持可空枚举值。因此,调整它:
public static class RaidioButtonListHelper
{
/// <summary>
/// Create a radiobutton list from viewmodel.
/// </summary>
public static MvcHtmlString RadioButtonList<TModel, TResult>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TResult>> expression, IEnumerable<SelectListItem> listOfValues = null)
{
var typeOfProperty = expression.ReturnType;
// Added by Darin Dimitrov to support nullable enums
var underlyingType = Nullable.GetUnderlyingType(typeOfProperty);
if (underlyingType != null)
{
typeOfProperty = underlyingType;
}
// End of addition
if (listOfValues == null && typeOfProperty.IsEnum)
{
listOfValues = new SelectList(Enum.GetValues(typeOfProperty));
}
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
// Ctreat table
TagBuilder tableTag = new TagBuilder("table");
tableTag.AddCssClass("radio-main");
// Create tr:s
var trTagLable = new TagBuilder("tr id=\"" + metaData.PropertyName + "Lables\"");
var trTagRadio = new TagBuilder("tr id=\"" + metaData.PropertyName + "Radios\"");
foreach (SelectListItem item in listOfValues)
{
var text = item.Text;
var value = item.Value ?? text;
// Generate an id to be given to the radio button field
var id = string.Format("{0}_{1}", metaData.PropertyName, value);
// Create the radiobuttons
var radioTag = htmlHelper.RadioButtonFor(expression, value, new { id = id }).ToHtmlString();
// Create the label for the radiobuttons.
var labelTag = htmlHelper.Label(id, HttpUtility.HtmlEncode(text));
// Add the lables and reaiobuttons to td:s
var tdTagLable = new TagBuilder("td style=\"padding-left: 10px; text-align: center\"");
var tdTagRadio = new TagBuilder("td style=\"padding-left: 10px; text-align: center\"");
tdTagLable.InnerHtml = labelTag.ToString();
tdTagRadio.InnerHtml = radioTag.ToString();
// Add tds: to tr:s
trTagLable.InnerHtml += tdTagLable.ToString();
trTagRadio.InnerHtml += tdTagRadio.ToString();
}
// Add tr:s to table
tableTag.InnerHtml = trTagLable.ToString() + trTagRadio.ToString();
//Return the table tag
return new MvcHtmlString(tableTag.ToString());
}
}现在,它将使用一个可空的枚举,如果相应属性的值为null,它将不会选择任何单选按钮。
https://stackoverflow.com/questions/12909595
复制相似问题