Client-side JavaScript ViewState Update in asp .ne

2019-02-18 16:21发布

I have stumbled upon the issue when I need to retract html controls I've added client-side using JavaScript after the postback (due to server-side validation - this is not optional).

Please tell me if the way I'm trying to achieve this is cr*p and there's a better way of doing this.

basically, what I'm doing is cloning a textbox control for up to 10 times on the page when the user hits "Add" and storing entered values from each of those texboxes in a hidden field to read from in the code behind. This works fine, however, when the server side validation doesn't pass after postback, all those dynamically added (cloned) texboxes disappear, since ViewState knows nothing about them.

I am considering 2 possible solution, both of which seem hacky:

  • Rebuild all cloned textboxes on document onload() using stored values in the hidden field

  • wrap the form in ajax update panel and place the cloned texboxes outside of it, thus, not refreshing this part of the screen on postback

now, is it possible to somehow "update" ViewState to make it aware of all the html controls I've added using client-side script? Any better ideas? I'd like to achieve this with client-side script, therefore not considering cloning textboxes on server-side, sorry.

1条回答
孤傲高冷的网名
2楼-- · 2019-02-18 16:51

You cannot modify the ViewState on the client side. If you do, you will invalidate the viewstate and receive an error on the postback.

In your case you might want to consider using javascript and jQuery to render the text boxes on the document ready event with the values stored in your hidden field. I'd recommend taking a look at jQuery templating, particularly if you can store your data as JSON in the hidden field (http://weblogs.asp.net/scottgu/archive/2010/10/04/jquery-templates-data-link-and-globalization-accepted-as-official-jquery-plugins.aspx).

查看更多
登录 后发表回答