Button Group of Radio Buttons is not setting any active Button with Bootstrap 3

前端 未结 2 1471
误落风尘
误落风尘 2021-01-26 01:46

I am trying to create a nice group of radio buttons with MVC and Bootstrap 3:

After selecting an option:

I store the value in the database but

相关标签:
2条回答
  • 2021-01-26 02:08

    This should work fine (It will select the radio button) as long as you set the correct value to the PrintType property of your view model which you are passing to your view.

    public ActionResult Index()
    {
      return View( new QuotePiecePrinting { PrintType=2});
    } 
    

    But if you want that to have the css class active, you can explicitly apply that css class to the parent label of the selected radio button on the document ready event. So add this to your page's script.

    $(function(){
       $("input[name='PrintType']:checked").closest("label.btn").addClass("active");
    });
    
    0 讨论(0)
  • 2021-01-26 02:18

    Try below code to render bootstrap radio button group with default select feature

    View:

    <div class="form-group">
        <div id="genderButtonGroup" class="btn-group btn-group-justified" role="group" aria-label="...">
            @{
                foreach (var item in Model.GenderList)
                {
                    <div class="btn-group" role="group">
                       <label class="btn btn-default">
                           @Html.RadioButtonFor(m => m.Gender, item.Key, (int)Model.Gender==item.Key ? new { @checked = "checked" } : null)
                           @item.Value
                      </label>
                    </div>
                }
            }
        </div>
        @Html.ValidationMessageFor(m => m.Gender)
    </div>
    

    Gender Enum:

    public enum Gender
    {
        Male = 0,
        Female = 1,
        RatherNotSay = 2
    }
    

    GenderList

    It is an IEnumerable property in Model class which can be populated in the Get controller action using the Gender Enum.

    public IEnumerable<KeyValuePair<int, string>> GenderList { get; set; }
    

    View will render as below:

    0 讨论(0)
提交回复
热议问题