MVC Razor:html文本框元素内是否包含条件

时间:2018-11-09 15:20:08

标签: html if-statement razor textbox

我正在尝试使用MVC Razor使用以下代码创建条件:

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

1 个答案:

答案 0 :(得分:1)

您可以创建一个if / else块,该块根据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"} })`
}

使用条件html属性:

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

如果@myMessage为null,Razor足够聪明,不会发出data_val_number。

关于条件属性的一些信息:

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

Conditional HTML Attributes using Razor MVC3

MVC 3: Conditionally Adding the Disabled Attribute with the HtmlHelpers