【问题标题】:Conditional html attribute with Html Helper带有 Html Helper 的条件 html 属性
【发布时间】:2016-01-20 00:37:26
【问题描述】:

我正在使用 Html 助手来创建一个复选框。在等待某些条件时,我想将 disabled 属性添加到 htmlAttribute 对象。我有以下代码:

@if (Model.IsAuthorized)
{
    @Html.CheckBoxFor(x => @Model.Property, new { @class = "input-class" })
}
else
{
    @Html.CheckBoxFor(x => @Model.Property, new { @class = "input-class", @disabled = "disabled" })
}

我想让这段代码更简洁。有没有办法在一行中有条件地添加某些html属性/没有条件块?

【问题讨论】:

标签: c# asp.net-mvc razor html-helper


【解决方案1】:

虽然你可以使用

@Html.CheckBoxFor(m => m.Property, Model.IsAuthorized ? (object)new { @class = "input-class", disabled = "disabled" } : (object)new { @class = "input-class"});

要在一行代码中执行此操作,在您的情况下可能会导致模型绑定失败。

CheckBoxFor() 方法生成 2 个输入,一个带有 value="True" 的复选框和一个带有 value="False" 的隐藏输入。在Property 的初始值为trueIsAuthorizedtrue 的情况下,该复选框被禁用并且不会发布值。但是隐藏的输入将被提交并绑定到您的模型,导致Property 成为false(当它应该是true

为了正确处理模型绑定,您需要 if

@if (Model.IsAuthorized)
{
    @Html.CheckBoxFor(x => m.Property, new { @class = "input-class" })
}
else
{
    @Html.HiddenFor(m => m.Property) // necessary to post back the initial value
    <input type="checkbox" @(Model.Property ? "checked" : null) disabled />
}

【讨论】:

    【解决方案2】:

    试试下面的代码:

    @{
     var attr = new { @class = "input-class" };
     if (Model.IsAuthorized)
     {
        attr = new { @class = "input-class", @disabled = "disabled" };
     }
    }
    @Html.CheckBoxFor(x => @Model.Property, attr)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-29
      • 1970-01-01
      • 2012-11-26
      • 2015-04-12
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多