mvc bind/post boolean to radiobutton

前端 未结 4 1022
有刺的猬
有刺的猬 2021-02-07 20:29

I have a column in my Model with a NULLABLE boolean value. Now on my View (for editing), I would like to bind that to two radiobuttons: Yes & No. If the value is null, then

4条回答
  •  轮回少年
    2021-02-07 20:52

    The use of multiple Html.RadioButtonFor (m => m.Foo, "true") seems to generate invalid HTML, because it generates controls with identical IDs:

    
    
    

    I have solved this by making the radio buttons directly in html:

    />
           
    />
    />

    make sure to name the radio buttons according to the used viewmodel, eg: Model.Filter.HasImage is named: Filter.HasImage to work with model binding

    The "html helper" looks like this:

        public static MvcHtmlString WriteCheckedIfTrue(this HtmlHelper htmlHelper, 
                                                       bool validation)
        {
            if(validation)
                return new MvcHtmlString("checked=\"checked\"");
    
            return new MvcHtmlString(string.Empty);
        }
    

提交回复
热议问题