4

我正在生成单选按钮列表,然后尝试在加载时选择一个选项,如下所示。

视图中的 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    

请建议我如何通过默认方式选择所需的单选按钮选项。

4

2 回答 2

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没有 的="",但这也可以。看,不是被识别的,而是属性本身,所以这就是检查第二个的原因。

于 2013-07-15T12:03:57.250 回答
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)
于 2013-07-15T12:38:35.540 回答