我正在使用这样的单选按钮,
<div class="form-group">
@Html.LabelFor(x => x.gender)
<div class="form-check">
<label class="form-check-label">
@Html.RadioButtonFor(x => x.gender, "Male")
Male
</label>
</div>
<div class="form-check">
<label class="form-check-label">
@Html.RadioButtonFor(x => x.gender, "Female")
Female
</label>
</div>
</div>
在这里,我有两个单选按钮在页面中呈现,我希望单选按钮被呈现,并且没有默认选择任何单选按钮,我该怎么做
我试过这样,但它不起作用
@Html.RadioButtonFor(x => x.gender, "Female", new { @checked = "true" })
更新
public class student
{
[DisplayName("Gender")]
[Required(ErrorMessage = "please select gender")]
public gender gender { get; set; }
}
public enum gender
{
male,
female
}
若要确保默认情况下未选择任何内容,请将属性设置为可为空:
public gender? gender { get; set; }
它的默认值将是 null
,这将确保没有选择任何内容,但是一旦用户发布表单Required
属性将不允许null
作为有效值。
另外,您现在正在使用字符串作为值,我不确定这是否适用于枚举。按照以下思路做一些事情会好得多:
@Html.RadioButtonFor(x => x.gender, gender.Female)
@Html.Label(gender.Female.ToString())
// Or you can stick to literals for labels as you do now.
// This however allows you to eventually turn this rendering code into a loop
试试这个;
@Html.RadioButtonFor(x => x.gender, "Female")