A B*_*gus 12 asp.net-mvc razor
在ASP.NET MVC应用程序中,我有两个单选按钮.根据模型中的布尔值,如何启用或禁用单选按钮?(单选按钮的值也是模型的一部分)
我的单选按钮目前看起来像这样 -
@Html.RadioButtonFor(m => m.WantIt, "false")
@Html.RadioButtonFor(m => m.WantIt, "true")
Run Code Online (Sandbox Code Playgroud)
在模型中,我有一个名为的属性model.Alive.如果model.Alive是true我想启用单选按钮,否则,如果model.Alive是false,我想禁用单选按钮.谢谢!
amh*_*hed 33
您可以像htmlAttributes一样直接传递值,如下所示:
@Html.RadioButtonFor(m => m.WantIt, "false", new {disabled = "disabled"})
@Html.RadioButtonFor(m => m.WantIt, "true", new {disabled = "disabled"})
Run Code Online (Sandbox Code Playgroud)
如果你需要检查model.Alive那么你可以做这样的事情:
@{
var htmlAttributes = new Dictionary<string, object>();
if (Model.Alive)
{
htmlAttributes.Add("disabled", "disabled");
}
}
Test 1 @Html.RadioButton("Name", "value", false, htmlAttributes)
Test 2 @Html.RadioButton("Name", "value2", false, htmlAttributes)
Run Code Online (Sandbox Code Playgroud)
希望有所帮助
小智 5
我的答案将与艾哈迈德的答案相同。唯一的问题是,WantIt 属性不会在提交时发送,因为由于禁用了 html 属性,它会被忽略。解决方案是在 RadioButtonFors 上方添加一个 HiddenFor ,如下所示:
@Html.HiddenFor(m => m.WantIt)
@Html.RadioButtonFor(m => m.WantIt, "false", new {disabled = "disabled"})
@Html.RadioButtonFor(m => m.WantIt, "true", new {disabled = "disabled"})
Run Code Online (Sandbox Code Playgroud)
这样所有的值都被呈现出来,并且你在提交时返回布尔值。