0

我正在使用 tagbuilder 创建一个自定义单选按钮助手。我正在使用帖子中建议的步骤:Custom helper for generate html tags for radio button and associated label,但对其进行了一些调整以使用 List 将值传递给单选按钮,有点像这样:-

@{
    List<SelectListItem> inventory = new List<SelectListItem>();
    inventory.Add(new SelectListItem { Text = "True", Value = bool.TrueString, Selected = true });
    inventory.Add(new SelectListItem { Text = "False", Value = bool.FalseString});
}

但是,即使我选择 true,它也总是将值设为 FALSE。下面是我构建标签生成器的代码,请让我知道我哪里出错了:

public static MvcHtmlString CustomRadioButtonFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, IEnumerable<SelectListItem> radioList)
        {
            StringBuilder radiobutton = new StringBuilder();
            TagBuilder radio = null;
            TagBuilder label = null;

            string[] propertyNameParts = expression.Body.ToString().Split('.');
            string propertyName = propertyNameParts.Last();
            string booleanStr = "";

            // get the value of the property
            Func<TModel, bool> compiled = expression.Compile();
            var name = ExpressionHelper.GetExpressionText(expression);
            var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            if (metadata.Model != null)
            {

                booleanStr = Convert.ToString(compiled(htmlHelper.ViewData.Model));

            }
            else
                booleanStr = string.Empty;

            // convert it to a boolean
            bool isChecked = false;
            Boolean.TryParse(booleanStr, out isChecked);

            foreach (SelectListItem item in radioList)
            {
                radio = new TagBuilder("input");
                label = new TagBuilder("label");
                label.InnerHtml = item.Text;
                radio.Attributes.Add("type", "radio");
                radio.Attributes.Add("name", name);
                radio.Attributes.Add("value", booleanStr);
                radiobutton.Append(label.ToString());
                radiobutton.Append(radio.ToString());
            }
            return MvcHtmlString.Create(radiobutton.ToString());
        }

任何帮助,将不胜感激。提前致谢!

4

0 回答 0