0

I'm developing and ASP.NET MVC app with C# and .NET Framework 4.7.

I want to add disabled attribute conditionally:

<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>

But this if (isDisabled) disabled doesn't work.

How can I add disabled attribute conditionally?

VansFannel
  • 45,055
  • 107
  • 359
  • 626
  • please reference this [question](https://stackoverflow.com/questions/2089468/conditionally-disable-html-dropdownlist). – fengqingtian Jul 28 '17 at 10:17
  • A note on your recently deleted question - most likely cause is you have a folder in your app named `Reports` (you deleted the question just as I was adding it) –  Sep 04 '17 at 09:45
  • @StephenMuecke Thanks. I have deleted the question because it had become a discussion. – VansFannel Sep 04 '17 at 09:59
  • Yes, I saw some of those grossly unfair comments by Bozhidar Stoinev :) –  Sep 04 '17 at 10:01
  • @StephenMuecke Yes, you are right. I have a folder named `Reports`. I have undelete it, https://stackoverflow.com/questions/46033566/iis-express-doesnt-show-index-cshtml-in-one-folder-but-in-other-it-shows. Please add your solution as an answer and I will accept it. Thanks a lot. – VansFannel Sep 04 '17 at 10:04

1 Answers1

0

Maybe you can try this :

@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"
    })

I haven't tested this code so plz let me know if it's correct.

JBO
  • 270
  • 1
  • 6