Search code examples
htmlif-statementrazortextbox

MVC Razor : if else condition inside html textbox element


i am trying to create a condition with MVC Razor with the code below:

@Html.TextBoxFor(m => Model.MyList[i].Value
new { autocomplete = "off", 
spellcheck = "false", data_val = 
Model.MyList[i].IsRequired.ToString().ToLower(), data_val_required = $"The 
field {Model.MyList[i].Description} is required", @: 
if(Model.MyList[i].FieldType == 0) { data_val_number = "Please enter     
`number" } })`

Solution

  • You could create an if/else block that generates the textbox based on the FieldType

    @if(Model.MyList[i].FieldType == 0)
    {
    @Html.TextBoxFor(m => Model.MyList[i].Value
    new { autocomplete = "off", 
    spellcheck = "false", data_val = 
    Model.MyList[i].IsRequired.ToString().ToLower(), data_val_required = $"The 
    field {Model.MyList[i].Description} is required", data_val_number = "Please enter     
    `number" } })`
    }
    else
    {
    @Html.TextBoxFor(m => Model.MyList[i].Value
    new { autocomplete = "off", 
    spellcheck = "false", data_val = 
    Model.MyList[i].IsRequired.ToString().ToLower(), data_val_required = $"The 
    field {Model.MyList[i].Description} is required"} })`
    }
    

    Or

    Use conditional html attributes:

    @{
      var myMessage = Model.MyList[i].FieldType == 0 ? "my message" : null;
    }
    
    @Html.TextBoxFor(m => Model.MyList[i].Value
    new { autocomplete = "off", spellcheck = "false", data_val = 
    Model.MyList[i].IsRequired.ToString().ToLower(), data_val_required = $"The 
    field {Model.MyList[i].Description} is required", data_val_number = "@myMessage" 
    })`
    

    Razor is smart enough to not emit data_val_number if @myMessage is null.

    Some info on conditional attributes:

    https://www.davidhaney.io/mvc4-conditional-html-attributes/

    Conditional HTML Attributes using Razor MVC3

    MVC 3: Conditionally Adding the Disabled Attribute with the HtmlHelpers