How can I make Html.CheckBoxFor() work on a string field?

前端 未结 4 1029
你的背包
你的背包 2021-01-02 02:15

I\'m using ASP.NET MVC3 with Razor and C#. I am making a form builder of sorts, so I have a model that has a collection of the following object:

public class         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 02:41

    One way is to create your own htmlhelper extension method.

        public static MvcHtmlString CheckBoxStringFor(this HtmlHelper html, Expression> expression)
        {
            // get the name of the property
            string[] propertyNameParts = expression.Body.ToString().Split('.');
            string propertyName = propertyNameParts.Last();
    
            // get the value of the property
            Func compiled = expression.Compile();
            string booleanStr = compiled(html.ViewData.Model);
    
            // convert it to a boolean
            bool isChecked = false;
            Boolean.TryParse(booleanStr, out isChecked);
    
            TagBuilder checkbox = new TagBuilder("input");
            checkbox.MergeAttribute("id", propertyName);
            checkbox.MergeAttribute("name", propertyName);
            checkbox.MergeAttribute("type", "checkbox");
            checkbox.MergeAttribute("value", "true");
            if (isChecked)
                checkbox.MergeAttribute("checked", "checked");
    
            TagBuilder hidden = new TagBuilder("input");
            hidden.MergeAttribute("name", propertyName);
            hidden.MergeAttribute("type", "hidden");
            hidden.MergeAttribute("value", "false");
    
            return MvcHtmlString.Create(checkbox.ToString(TagRenderMode.SelfClosing) + hidden.ToString(TagRenderMode.SelfClosing));
        }
    

    The usage is the same as CheckBoxFor helper (e.Value is a string)

    @Html.CheckBoxStringFor(e => e.Value)
    

提交回复
热议问题