使用razor@Html帮助程序的条件Html属性

使用razor@Html帮助程序的条件Html属性,html,asp.net-mvc,razor,Html,Asp.net Mvc,Razor,我正在尝试向通过@html helper函数生成的html添加一个disable属性,但似乎无法在html helper的attrib参数中工作。我下面的内容仍将为html禁用写入。。。但我无法移除它,因为助手无法工作 我定义了一个变量: @{ var displayItem = (Model.TypeId == 100) } @Html.TextBox("listitem", "", new {@class = "form-control", @disabled = (@displayIte

我正在尝试向通过@html helper函数生成的html添加一个disable属性,但似乎无法在html helper的attrib参数中工作。我下面的内容仍将为html禁用写入。。。但我无法移除它,因为助手无法工作

我定义了一个变量:

@{ var displayItem = (Model.TypeId == 100) }

@Html.TextBox("listitem", "", new {@class = "form-control", @disabled = (@displayItem ? "" : "disabled")})
但因为我必须列出参数@disabled,它会生成如下html:

<input class="form-control"  disabled="" id="listitem" name="listitem"  type="text" value="" />

因为列出了disabled,所以它会禁用输入。但是,除非我给它一个参数名,否则html助手是不起作用的

如何在参数列表中写入禁用项,以便在不应禁用的情况下,禁用项完全不显示?

您可以使用

@{ var displayItem = (Model.TypeId == 100) }
@Html.TextBox("listitem", "", displayItem ? (object)new { @class = "form-control", disabled = "disabled" } : (object)new { @class = "form-control"});

或者一个简单的
if

@(if Model.TypeId == 100)
{
    @Html.TextBox("listitem", "", new {@class = "form-control", disabled = "disabled" })
}
else
{
    @Html.TextBox("listitem", "", new {@class = "form-control" })
}
请注意,禁用控件的值不会提交,因此您可以使用的
只读属性可能更合适

@{ var displayItem = (Model.TypeId == 100) }
@Html.TextBox("listitem", "", displayItem ? (object)new { @class = "form-control", disabled = "disabled" } : (object)new { @class = "form-control"});

或者一个简单的
if

@(if Model.TypeId == 100)
{
    @Html.TextBox("listitem", "", new {@class = "form-control", disabled = "disabled" })
}
else
{
    @Html.TextBox("listitem", "", new {@class = "form-control" })
}

请注意,禁用控件的值不会提交,因此
只读属性可能更合适

您还可以使用字典并将其传递给html帮助程序:

@{
    var attributes = new Dictionary<string, object>
    {
        { "class", "form-control" }
    };

    if (Model.TypeId == 100)
    {
        attributes.Add("disabled", "disabled");
    }
}

@Html.TextBox("listitem", "", attributes)
@{
var属性=新字典
{
{“类”,“窗体控件”}
};
如果(Model.TypeId==100)
{
添加(“禁用”、“禁用”);
}
}
@TextBox(“listitem”、“属性”)

您还可以使用字典并将其传递给html帮助程序:

@{
    var attributes = new Dictionary<string, object>
    {
        { "class", "form-control" }
    };

    if (Model.TypeId == 100)
    {
        attributes.Add("disabled", "disabled");
    }
}

@Html.TextBox("listitem", "", attributes)
@{
var属性=新字典
{
{“类”,“窗体控件”}
};
如果(Model.TypeId==100)
{
添加(“禁用”、“禁用”);
}
}
@TextBox(“listitem”、“属性”)

好的,我想知道构造属性参数是否还有其他技巧,但我想没有。好的,我想知道构造属性参数是否还有其他技巧,但我想没有。德克萨斯州。