Razor中TextAreaFor的Disabled属性无法生效问题求助
Razor中TextAreaFor的Disabled属性不生效问题解决办法
问题原因
HTML的disabled是布尔属性,只要该属性存在,无论其值是什么(哪怕是disabled="false"),元素都会被禁用。你当前代码中,当Model.Question.IsStop为false时,会生成disabled="false"的属性,这依然会让文本域处于禁用状态,导致不符合预期。
解决方案
方案1:条件渲染不同的TextAreaFor
通过if-else判断,根据状态决定是否添加disabled属性:
@if (Model.Question.IsStop) { @Html.TextAreaFor(m => Model.Question.StopReason, new { @style = "height:60px;width:300px", @disabled = "disabled" }) } else { @Html.TextAreaFor(m => Model.Question.StopReason, new { @style = "height:60px;width:300px" }) }
方案2:动态构建HTML属性字典
先创建基础属性字典,再根据条件添加disabled属性:
var htmlAttrs = new Dictionary<string, object> { { "style", "height:60px;width:300px" } }; if (Model.Question.IsStop) { htmlAttrs.Add("disabled", "disabled"); } @Html.TextAreaFor(m => Model.Question.StopReason, htmlAttrs)
方案3:利用C# 6+的条件匿名属性(简洁写法)
当条件不满足时,将disabled属性设为null,Razor会自动忽略该属性:
@Html.TextAreaFor(m => Model.Question.StopReason, new { @style = "height:60px;width:300px", @disabled = Model.Question.IsStop ? "disabled" : null })
内容的提问来源于stack exchange,提问作者Akira
相关产品推荐
相关产品推荐

