无法从自定义单选按钮中的SelectListItem获取正确的布尔值

时间:2016-05-27 06:29:18

标签: asp.net-mvc radio-button selectlistitem tagbuilder mvchtmlstring

我正在使用tagbuilder创建自定义单选按钮帮助程序。我正在使用帖子中建议的步骤:Custom helper for generating 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());
        }

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

0 个答案:

没有答案