Home Set Html.TextBoxFor not editable depending on a Model value
Reply: 3

Set Html.TextBoxFor not editable depending on a Model value

VansFannel Published in 2017-09-13 08:19:02Z

This question already has an answer here:

  • Enabling & disabling a textbox in razor view (ASP.Net MVC 3) 2 answers

I'm developing an ASP.NET MVC 5 app with Razor, C# and .NET Framework 4.7.

I want to make it a textbox not editable if Model.IsChinaProduct is true.

I have this piece of code in a View:

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

I want to add the disabled attribute if Model.IsChinaProduct is true, but that code shows me the following error:

Error CS0746 Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

How can I add the disabled attribute if Model.IsChinaProduct is true?

Maybe disabled is not the right attribute.

ChrFin Reply to 2017-09-13 08:26:33Z

AFAIK you can't, because there is no disabled="false", meaning you should do something like that:

    var htmlAttributes = Model.IsChinaProduct ? (object)
        new { @class = "productClass", readonly = "readonly" }
        : new { @class = "productClass", @onkeydown = "IsValidKey(event);" };
@Html.TextBoxFor(m => m.Configurations[index].PkgRatio, htmlAttributes)
SeM - ՍեՄ
SeM - ՍեՄ Reply to 2017-09-13 08:30:21Z

For setting it ReadOnly, try this:

   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)
Dan Nguyen
Dan Nguyen Reply to 2017-09-13 08:41:56Z

Dont use TextBoxFor if IsChinaProduct = true Try DisplayFor combine with HiddenFor instead

like this

@if (Model.IsChinaProduct)
    @Html.HiddenFor(m => m.Configurations[index].PkgRatio)
     @Html.DisplayFor(m => m.Configurations[index].PkgRatio)
     @Html.TextBoxFor(m => m.Configurations[index].PkgRatio)
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.366089 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO