设置Html.TextBox不可编辑,具体取决于Model值

时间:2017-09-13 08:19:03

标签: c# asp.net asp.net-mvc razor

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

如果Model.IsChinaProduct为真,我想将其设为不可编辑的文本框。

我在视图中有这段代码:

@Html.TextBoxFor(m => m.Configurations[index].PkgRatio, new { @class = "productClass", @onkeydown = "IsValidKey(event);" @if (Model.IsChinaProduct) disabled})

如果disabled为true,我想添加Model.IsChinaProduct属性,但该代码显示以下错误:

  

错误CS0746无效的匿名类型成员声明符。匿名类型   必须使用成员作业,简单名称或成员声明成员   会员访问。

如果disabled为真,我如何添加Model.IsChinaProduct属性?

更新
也许残疾不是正确的属性。

3 个答案:

答案 0 :(得分:0)

AFAIK你不能,因为没有disabled="false",这意味着你应该这样做:

@{
    var htmlAttributes = Model.IsChinaProduct ? (object)
        new { @class = "productClass", readonly = "readonly" }
        : new { @class = "productClass", @onkeydown = "IsValidKey(event);" };
}
@Html.TextBoxFor(m => m.Configurations[index].PkgRatio, htmlAttributes)

答案 1 :(得分:0)

要设置 ReadOnly ,请尝试以下操作:

@{
   object displayMode = (Model.IsChinaProduct) ? new { @class = "productClass", @onkeydown = "IsValidKey(event);" } 
                                               : new { @class = "productClass", @onkeydown = "IsValidKey(event);" readonly = "readonly"};
   @Html.TextBoxFor(m => m.Configurations[index].PkgRatio, displayMode)
}

答案 2 :(得分:0)

如果IsChinaProduct = true,请不要使用TextBoxFor 尝试使用DisplayFor与HiddenFor结合使用

像这样

@if (Model.IsChinaProduct)
 {
    @Html.HiddenFor(m => m.Configurations[index].PkgRatio)
     @Html.DisplayFor(m => m.Configurations[index].PkgRatio)
 }
 else
 {
     @Html.TextBoxFor(m => m.Configurations[index].PkgRatio)
 }
相关问题