How can I create a RadioButtonList in a MVC View via HTML class ( Razor syntax )

前端 未结 1 472
名媛妹妹
名媛妹妹 2020-12-22 03:32

I need to show my list in a RadioButtonList , some thing like this: @Html.RadioButtonList(\"FeatureList\", new SelectList(ViewBag.Features)) But as you know there is no Radi

相关标签:
1条回答
  • 2020-12-22 03:41

    Html.RadioButton does not take (string, SelectList) arguments, so I suppose the blank list is expected ;)

    You could 1)

    Use a foreach over your radio button values in your model and use the Html.RadioButton(string, Object) overload to iterate your values

    // Options could be a List<string> or other appropriate 
    // data type for your Feature.Name
    @foreach(var myValue in Model.Options) {
        @Html.RadioButton("nameOfList", myValue)
    }
    

    or 2)

    Write your own helper method for the list--might look something like this (I've never written one like this, so your mileage may vary)

    public static MvcHtmlString RadioButtonList(this HtmlHelper helper, 
        string NameOfList, List<string> RadioOptions) {
    
        StringBuilder sb = new StringBuilder();
    
        // put a similar foreach here
        foreach(var myOption in RadioOptions) {
            sb.Append(helper.RadioButton(NameOfList, myOption));
        }
    
        return new MvcHtmlString(sb.ToString());
    }
    

    And then call your new helper in your view like (assuming Model.Options is still List or other appropriate data type)

    @Html.RadioButtonList("nameOfList", Model.Options)
    
    0 讨论(0)
提交回复
热议问题