5

I am dynamically generating the form based on the drop down selected. The form consists of fields (data entry for decimal values + few text fields). Have to add all the decimal values at the end and update the Total TextBox with that value. Total Textbox is disabled.

When I click Save button on the form after the user have entered their values, whole form is persisted in viewstate except the disabled textbox. When I enable the textbox, everything works fine. Mind you, I am dynamically generating the form and updating the value of the total textbox using javascript to calculate (adding all decimal fields).

P.S. I am doing everything right for persisting the viewstate.

So what has the enabled/disabled got bearing on the viewstate

DotNetInfo
  • 3,344
  • 6
  • 33
  • 39

4 Answers4

8

Basically, I added two statements to get it working.

txtBox.Attributes.Add("readonly", "readonly");
txtBox.Style.Add("color","gray");

When I used txtBox.Enabled = false, it didn't persist viewstate but did it alternatively using above two statements in my code-behind page

DotNetInfo
  • 3,344
  • 6
  • 33
  • 39
  • 1
    A little more on the issue on a question I posted a while back: http://stackoverflow.com/questions/1060518/strange-behavior-using-html-readonly-readonly-vs-javascript-element-readonl/1063609#1063609 – Cᴏʀʏ Jun 11 '11 at 17:38
  • @DotNetInfo, but what if the "txtBox" control cannot be accessed by intellisense, as it's deep inside a DetailsView or GridView. Unfortunately FindControl("txtBox") always brings back null in page_load. – Fandango68 Jun 02 '15 at 02:29
2

Yes, disabled form element will not send it's value to server side, you can look request header. disabled element not appeared at "get" or "post" collection.

If you want set user can't edit it, you can set it as readonly.

xling
  • 252
  • 1
  • 9
0

Please create custom text box rather than using actual textbox instance.

inherit textbox in your custom textbox and add this textbox in your dynamic form.

0

Add javascript on the page:

function enableTextBoxes() {
            $("input[type='text'][disabled='disabled']").removeAttr("disabled");
        }

And add to server code (in Page_Load, PreRender or some else method)

ClientScript.RegisterOnSubmitStatement(typeof(Page), "enableTextBoxes", "enableTextBoxes();");

If you use UpdatePanels then utilize the ScriptManager.RegisterOnSubmitStatement method

Yuriy Rozhovetskiy
  • 22,270
  • 4
  • 37
  • 68
  • I already tried that before but it didn't work. Basically, text box displays in disabled state but the value doesn't get set on postback. Textbox displays with no value. I used ("readonly", "readonly") attribute, it works fine but doesn't show textbox in disabled state (grayed out) – DotNetInfo Jun 11 '11 at 14:27
  • @DotNetInfo you have to remove hard-coding the Enabled="false" or ReadOnly="true" from the textbox control first. – Fandango68 Jun 02 '15 at 02:28