在 MVC 中使用 Razor 时如何取消选中默认单选按钮?
How to make the default radio button to be unchecked while using Razor in MVC?
我正在使用这样的单选按钮,
<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
}
试试这个;
@Html.RadioButtonFor(x => x.gender, "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
我正在使用这样的单选按钮,
<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
}
试试这个;
@Html.RadioButtonFor(x => x.gender, "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