gpt4 book ai didi

c# - 带有 Html Helper 的条件 html 属性

转载 作者:行者123 更新时间:2023-11-30 13:55:24 25 4
gpt4 key购买 nike

我正在使用 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 属性/没有条件 block ?

最佳答案

虽然你可以使用

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

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

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

为了正确处理模型绑定(bind),您需要 if block

@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 />
}

关于c# - 带有 Html Helper 的条件 html 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34889537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com