0

現在、このコードを使用して、MVC4 を使用して RadioButtonList を実装しています。

ご覧のとおり、その関数には htmlAttributes パラメータがありません。だから私はそれを追加したいのですが、ここに問題があります。RadioButtonFor() の htmlAttributes が ID で占められていることを確認してください。

追加しようとしましたが、ループの ID が既に存在するため、エラーがスローされます。

public static class HtmlExtensions
{
    public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression,
        IEnumerable<SelectListItem> listOfValues)
    {
        return htmlHelper.RadioButtonForSelectList(expression, listOfValues, null);
    }

    public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression,
        IEnumerable<SelectListItem> listOfValues,
        object htmlAttributes)
    {
        return htmlHelper.RadioButtonForSelectList(expression, listOfValues, new RouteValueDictionary(htmlAttributes));
    }

    public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression,
        IEnumerable<SelectListItem> listOfValues,
        IDictionary<string, object> htmlAttributes)
    {
        var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        var sb = new StringBuilder();
        if (listOfValues != null)
        {
            foreach (SelectListItem item in listOfValues)
            {
                var id = string.Format(
                    "{0}_{1}",
                    metaData.PropertyName,
                    item.Value
                );

                var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString();
                sb.AppendFormat(
                    "{0}<label for=\"{1}\">{2}</label>",
                    radio,
                    id,
                    HttpUtility.HtmlEncode(item.Text)
                );
            }
        }
        return MvcHtmlString.Create(sb.ToString());
    }
}
4

1 に答える 1

2

3 番目の方法では、作成中のラジオ ボタンに渡される html 属性はnew { id = id }. それをメソッドのパラメーターに置き換えてみてください。

更新しました

html 属性に id を含め、各ループ反復で id に新しい値を割り当てます。

if (listOfValues != null)
{
    if (!htmlAttributes.ContainsKey("id"))
    {
        htmlAttributes.Add("id", null);
    }
    foreach (SelectListItem item in listOfValues)
    {
        var id = string.Format(
            "{0}_{1}",
            metaData.PropertyName,
            item.Value
        );
        htmlAttributes["id"] = id;
        var radio = htmlHelper.RadioButtonFor(expression, item.Value, htmlAttributes).ToHtmlString();
        sb.AppendFormat(
            "{0}<label for=\"{1}\">{2}</label>",
            radio,
            id,
            HttpUtility.HtmlEncode(item.Text)
        );
    }
}
于 2013-01-14T05:46:12.390 に答える