MVC3 EditorTemplate for a nullable boolean using RadioButtons

前端 未结 6 1893
深忆病人
深忆病人 2020-12-05 10:55

I have a property on one of my objects that is a nullable boolean, I want my logic to have true represent Yes, false to be No and null to be N/A. Now because I am going to h

6条回答
  •  忘掉有多难
    2020-12-05 11:26

    How about some extension method fun to keep that "one line to rule them all". :-)

    public static class DictionaryHelper
    {
        // This returns the dictionary so that you can "fluently" add values
        public static IDictionary AddIf(this IDictionary dictionary, bool addIt, TKey key, TValue value)
        {
            if (addIt)
                dictionary.Add(key, value);
            return dictionary;
        }
    }
    

    And then in your template file you simply change the signature of how you are adding the additional parameters including the checked="checked" attribute to the element.

    @model bool?
    
    @Html.RadioButtonFor(x => x, true, new Dictionary() .AddIf(true, "id", ViewData.TemplateInfo.GetFullHtmlFieldId("") + "Yes") .AddIf(Model.HasValue && Model.Value, "checked", "checked") ) @Html.RadioButtonFor(x => x, false, new Dictionary() .AddIf(true, "id", ViewData.TemplateInfo.GetFullHtmlFieldId("") + "No") .AddIf(Model.HasValue && !Model.Value, "checked", "checked") ) @Html.RadioButtonFor(x => x, "null", new Dictionary() .AddIf(true, "id", ViewData.TemplateInfo.GetFullHtmlFieldId("") + "NA") .AddIf(!Model.HasValue, "checked", "checked") )

提交回复
热议问题