ASP.NET MVC Razor语法:如何禁用单选按钮

17
在一个ASP.NET MVC应用程序中,我有两个单选按钮。根据模型中的布尔值,我如何启用或禁用这些单选按钮?(单选按钮的值也是模型的一部分)
我的单选按钮目前看起来像这样 -
            @Html.RadioButtonFor(m => m.WantIt, "false")  
            @Html.RadioButtonFor(m => m.WantIt, "true")  
在这个模型中,我有一个名为model.Alive的属性。如果model.Alivetrue,我想要启用单选框;如果model.Alivefalse,我想要禁用单选框。 谢谢!

将CSS设置为启用、禁用或隐藏/显示单选按钮。您也可以完全不呈现单选按钮。 - Nate-Wilkins
有没有标准的“Razor/ASP.NET/MVC”方法来做这件事? - A Bogus
如果(Model.Alive){setcss enabled or @Html.RadioButonFor//Display radio buttons}只需检查模型状态是否为真,设置属性或根本不创建单选按钮。 - Nate-Wilkins
3个回答

43
您可以直接将值作为htmlAttributes传递,如下所示:
@Html.RadioButtonFor(m => m.WantIt, "false", new {disabled = "disabled"})  
@Html.RadioButtonFor(m => m.WantIt, "true", new {disabled = "disabled"})

如果您需要检查 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)
希望这可以帮到你。

6

我的答案与Ahmed的一样。唯一的问题是,由于被禁用的HTML属性而被忽略,因此WantIt属性在提交时不会被发送。解决方法是在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"})

那样的话,所有的值都会被渲染,并且在提交时会返回布尔值。

0

或者为RadioButtonFor提供一个重载?

public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, bool isDisabled, object htmlAttributes)
    {
        var linkAttributes = System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
        Dictionary<string, object> htmlAttributesDictionary = new Dictionary<string, object>();
        foreach (var a in linkAttributes)
        {
            if (a.Key.ToLower() != "disabled")
            {
                htmlAttributesDictionary.Add(a.Key, a.Value);
            }

        }

        if (isDisabled)
        {
            htmlAttributesDictionary.Add("disabled", "disabled");
        }

        return InputExtensions.RadioButtonFor<TModel, TProperty>(htmlHelper, expression, value, htmlAttributesDictionary);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接