如何有条件地添加禁用属性?

时间:2017-07-28 09:49:16

标签: c# asp.net razor

我正在开发使用C#和.NET Framework 4.7的ASP.NET MVC应用程序。

我想有条件地添加禁用属性:

<div class="group">
    @{bool isDisabled; }

    @if ((Model.VariableDataList[levelIndex].VariableDataForLevel[vDataIndex].VariableDataId == "01") ||
        (Model.VariableDataList[levelIndex].VariableDataForLevel[vDataIndex].VariableDataId == "10"))
    {
        isDisabled = true;
    }
    else
    {
        isDisabled = false;
    }

    @Html.DropDownListFor(
        m => m.VariableDataList[levelIndex].VariableDataForLevel[vDataIndex].VariableDataId,
        new SelectList(Model.variableDataItems, "Id", "Name",
        Model.VariableDataList[levelIndex].VariableDataForLevel[vDataIndex].VariableDataId),
        new {
            @onchange = "OnChangeVariableDataId(this);",
            data_level_index = @levelIndex,
            data_list_index = @vDataIndex,
            if (isDisabled) disabled
        })
</div>

但这if (isDisabled) disabled无效。

如何有条件地添加disabled属性?

1 个答案:

答案 0 :(得分:0)

也许你可以试试这个:

@Html.DropDownListFor(
    m => m.VariableDataList[levelIndex].VariableDataForLevel[vDataIndex].VariableDataId,
    new SelectList(Model.variableDataItems, "Id", "Name",
    Model.VariableDataList[levelIndex].VariableDataForLevel[vDataIndex].VariableDataId),
    new {
        @onchange = "OnChangeVariableDataId(this);",
        data_level_index = @levelIndex,
        data_list_index = @vDataIndex,
        disabled = isDisabled ? "disabled" : "false"
    })

我没有测试过这段代码,所以请告诉我它是否正确。