【问题标题】:ASP.NET MVC disable radio buttons with Razor syntaxASP.NET MVC 使用 Razor 语法禁用单选按钮
【发布时间】:2013-01-26 18:31:35
【问题描述】:

在 ASP.NET MVC 应用程序中,我有两个单选按钮。根据模型中的布尔值,如何启用或禁用单选按钮? (单选按钮的值也是模型的一部分)

我的单选按钮目前看起来像这样 -

            @Html.RadioButtonFor(m => m.WantIt, "false")  
            @Html.RadioButtonFor(m => m.WantIt, "true")  

在模型中,我有一个名为model.Alive 的属性。如果model.Alivetrue 我想启用 单选按钮,否则如果model.Alivefalse,我想禁用 单选按钮。 谢谢!

【问题讨论】:

  • 设置 css 以启用禁用或隐藏显示单选按钮。您也根本无法呈现单选按钮。
  • 是否有标准的“Razor/ASP.NET/MVC”方式来执行此操作?
  • if (Model.Alive) { setcss enabled or @Html.RadioButonFor//Display radio buttons } 只需检查模型状态是否为 true 设置属性或根本不创建单选按钮

标签: asp.net-mvc razor


【解决方案1】:

我的答案与艾哈迈德的相同。唯一的问题是,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"})

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

【讨论】:

    【解决方案2】:

    或者为 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);
        }
    

    【讨论】:

      【解决方案3】:

      您可以像这样直接将值作为 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)
      

      希望有帮助

      【讨论】:

      • 很好的答案!谢谢我!
      猜你喜欢
      • 2022-01-10
      • 2010-09-07
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 2021-07-14
      • 2011-02-22
      相关资源
      最近更新 更多