我正在生成radiobutton列表,然后尝试在加载时选择一个选项,如下所示。
View中的Foreach循环
@foreach (var myListItem in Model.MyList)
{
@Html.RadioButtonFor(m => m.MyType,myListItem.MyType, new {id = myListItem.MyType, @Checked = (Model.MyTypeId == myListItem.MyTypeId) })
@myListItem.MyType
}
尽管HTML生成正确(请参阅下文)。即使Model.MyTypeId = 0
。
为视图生成HTML
<input id="0" name="MyType" value="Option One" CHECKED="True" type="radio">Option One
<input id="1" name="MyType" value="Option Two " CHECKED="False" type="radio">Option Two
请建议我如何通过deafult选择所需的单选按钮选项。
答案 0 :(得分:5)
HTML实际上并不正确。你需要在这些方面做更多的事情:
@foreach (var myListItem in Model.MyList)
{
if (Model.MyTypeId == myListItem.MyTypeId)
{
@Html.RadioButtonFor(m => m.MyType,myListItem.MyType,
new
{
id = myListItem.MyType,
@Checked = ""
})
}
else
{
@Html.RadioButtonFor(m => m.MyType,myListItem.MyType,
new
{
id = myListItem.MyType,
})
}
@myListItem.MyType
}
虽然我无法验证完全输出,但它看起来应该是这样的:
<input id="0" name="MyType" value="Option One" CHECKED type="radio">
您可能必须使用null
来生成CHECKED
而不使用=""
,但这也没关系。请注意,识别的值不是属性本身,所以这就是选中第二个的原因。
答案 1 :(得分:2)
无论何时我需要从查询创建的单选按钮列表,我总是可以使用此RadioButtonListFor扩展方法。像魅力一样:
// jonlanceley.blogspot.com/2011/06/mvc3-radiobuttonlist-helper.html
public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> listOfValues)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
sb.Append("<span class='RadioButtonListFor'> ");
if (listOfValues != null)
{
// Create a radio button for each item in the list
foreach (SelectListItem item in listOfValues)
{
// Generate an id to be given to the radio button field
var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
// Create and populate a radio button using the existing html helpers
var htmlAttributes = new Dictionary<string, object>();
htmlAttributes.Add("id", id);
if (item.Selected)
htmlAttributes.Add("checked", "checked");
var radio = htmlHelper.RadioButtonFor(expression, item.Value, htmlAttributes);
// Create the html string that will be returned to the client
// e.g. <label<input data-val="true" data-val-required="You must select an option" id="TestRadio_1" name="TestRadio" type="radio" value="1" />Line1</label>
sb.AppendFormat("<label>{0} {1}</label> ", radio, HttpUtility.HtmlEncode(item.Text));
}
}
sb.Append(" </span>");
return MvcHtmlString.Create(sb.ToString());
}
现在,您可以从内存中的任何集合生成单选按钮,通常作为ViewModel上的属性,如下所示:
public int SelectedPaymentMethodId { get; set; }
public IEnumerable<SelectListItem> PaymentMethodChoices
{
get
{
return from x in dataSourceFoo
select new SelectListItem {
Text = x.TextThing, Value = x.Id, Selected = (x.Id == SelectedPaymentMethodId)
};
}
}
您的视图非常简单:
@Html.RadioButtonListFor(model => model.SelectedPaymentMethodId, Model.PaymentMethodChoices)