如何检查默认单选按钮是否有条件? 以下是我的代码:
枚举
public enum yesNo
{
Yes = 0,
No = 1
}
查看
<div class="form-group">
@Html.LabelFor(model => model.Member_Addiction, new { @class = " col-md-3" })
<div class="col-md-4">
@foreach (var e in Enum.GetValues(typeof(RKDYM.clsEnums.yesNo)))
{
<label class="radio-inline">
@Html.RadioButtonFor(model => model.Member_Addiction, (int)e, new { htmlAttributes = new { @class = "form-control"} })@e.ToString()
</label>
}
</div>
@Html.ValidationMessageFor(model => model.Member_Addiction)
</div>
模型
[DisplayName("Do you have addiction?")]
public bool Member_Addiction { get; set; }
答案 0 :(得分:0)
在模型的构造函数中设置默认值。 我尝试了以下代码并且它可以工作(它设置默认值,如果用户更改值,它会向控制器返回正确的值)。
public enum yesNo
{
Yes = 0,
No = 1
}
public class TestModel
{
public TestModel()
{
this.Member_Addiction = false;
}
[DisplayName("Do you have addiction?")]
public bool Member_Addiction { get; set; }
}
@using (Html.BeginForm())
{
<div class="form-group">
@Html.LabelFor(model => model.Member_Addiction, new { @class = " col-md-3" })
<div class="col-md-4">
@foreach (TestProject.Models.yesNo e in Enum.GetValues(typeof(TestProject.Models.yesNo)))
{
<label class="radio-inline">
@{ if (e == TestProject.Models.yesNo.No)
{
@Html.RadioButtonFor(model => model.Member_Addiction, false)@e.ToString()
}
else
{
@Html.RadioButtonFor(model => model.Member_Addiction, true)@e.ToString()
}
}
</label>
}
</div>
@Html.ValidationMessageFor(model => model.Member_Addiction)
</div>
<button type="submit">OK</button>
}
P.S。也许你可以找到比使用&#34更好的溶剂;如果&#34;在您的视图中声明。
答案 1 :(得分:-1)
我已更换以下行
new { htmlAttributes = new { @class = "form-control"} }
与
new { @class = "form-control", @checked = "checked" }