Button Group of Radio Buttons没有设置任何带Bootstrap 3的活动按钮

时间:2016-02-19 17:14:36

标签: c# asp.net-mvc twitter-bootstrap razor

我正在尝试用MVC和Bootstrap 3创建一组很好的单选按钮:

enter image description here

选择选项后:

enter image description here

我将值存储在数据库中,但当我再次显示View时,没有选择任何内容:

enter image description here

模型是:

[Table("QuotePiecePrinting")]
public partial class QuotePiecePrinting
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Display(Name = "Tipo de Impressão")]
    public int PrintType { get; set; }
}

视图是:

<div class="form-group">
    @Html.LabelFor(model => model.PrintType, htmlAttributes: new { @class = "control-label col-xs-12 col-sm-4 col-md-3" })
    <div class="col-xs-6 col-sm-3 col-md-7 col-lg-6">
        <div class="btn-group btn-group-justified" data-toggle="buttons">
            <label class="btn btn-primary">
                @Html.RadioButtonFor(model => model.PrintType, "1") Digital
            </label>
            <label class="btn btn-primary">
                @Html.RadioButtonFor(model => model.PrintType, "2") Offset Convencional
            </label>
            <label class="btn btn-primary">
                @Html.RadioButtonFor(model => model.PrintType, "3") Offset UV
            </label>
        </div>
    </div>
</div>

为什么当我再次显示视图时,未反映所选选项的存储值?

该值正确存储在数据库中。

2 个答案:

答案 0 :(得分:2)

只要您将正确的值设置为要传递给视图的视图模型的PrintType属性,这应该可以正常工作(它将选择单选按钮)。

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

但是如果您希望css类处于活动状态,则可以将该css类显式应用于文档就绪事件中所选单选按钮的父标签。所以将它添加到页面的脚本中。

$(function(){
   $("input[name='PrintType']:checked").closest("label.btn").addClass("active");
});

答案 1 :(得分:0)

尝试以下代码,使用默认选择功能

呈现自举单选按钮组

查看:

<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>

性别枚举:

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

GenderList

它是Model类中的IEnumerable属性,可以使用Gender Enum在Get控制器操作中填充。

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

视图将呈现如下:

enter image description here