Client-side JavaScript ViewState Update in asp .net forms - javascript

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.

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).

Related

Dropdownlist Postback interferes with Javascript

My ASP page has a DropDownList (DDL) and a bunch of checkboxes. When my user selects a DDL item, I have some JS/jQuery code to make several checkboxes invisible according to some logic. However, the postback of the DDL, needed to run the C# code-behind event handler, causes a redraw of the entire page and makes all checkboxes visible.
How can I prevent the postback from wiping out the actions of the JS? Should I store visibility bits in something like ViewState?
Is it possible to have the JS code run AFTER the postback, instead of before?
Is it possible/easy to use CallBack instead of PostBack for the ASP DropDownList? I was thinking that the fun of Ajax was avoiding postbacks and only updating the control instead of the entire page.
Well if the dropdown posts back in the same action that you flip the switch for the checkboxes, why not then put the logic to show/hide checkboxes on the server instead of the client? You can use the hidden field approach, and that would work fine.
The callback means the UI needs updated by JavaScript. I don't know what all the postback updates, but you would have to send everything up via JSON, and refresh the UI via JavaScript. So only you can make that call.

How can I access a javascript variable from the codebehind of an ascx?

Specifically, I have an ascx control, let's assume it injects the javascript var x=5.
The ascx control contains a button, which when clicked does x++;
x is then 6.
When someone puts my control on their page, and clicks a button that posts back (the button is their own), I want to let them retrieve the value of x in the code behind.
Is there a solution that would allow this? The closest I can think of is to put a hidden field in the ascx, and store the value in the hidden field when it is updated. Then in my codebehind, on postback, I can do myControl.hiddenField.value to retrieve the result.
I haven't tried this yet as I am wondering if there is a better way. Also I'm not sure if the updated value of hidden field will register when it is altered via javascript, although being a post, I would hope it is.
Thoughts?
Edit: In fact, using a getter I could hide away the hidden field and just allow direct access to the value... if that solution is the best...
Yes, your own answer is the best one...especially with your edit! Form fields are how these two tiers communicate with one another. You could potentially invoke an ajax post with a some dynamically built get / post parameters, but this wouldn't be any better...
Your idea is already the best approach you can take. I don't think you can go with the Ajax request option proposed by Timbo because yours is an ascx control that can be placed in many different forms and how would you determine were will you send the post or get request?
In conclusion, your approach is just fine and there's nothing inefficient with it.

retaining selected value of ASP.NET DropDownList re-built by JavaScript

I converted a 100% ASP.NET driven form to using nearly all AJAX based architecture except that it doesn't submit the data using AJAX call, yet. It does a full page postback. And because the button submissions are still tied to so much functionality (it's a global button custom control with multiple buttons), I chose not to convert them over to AJAX yet.
Every piece of data submits fine, except for one use-case. It's a dropdown that is dependent from another dropdown. So now, when the value of dropdown 1 changes by the end user, dropdown 2 gets rebuilt from AJAX calls (JavaScript). Note, dropdown 1's options NEVER change in the life of the application. When the form is submitted after that workflow, we lose the value of dropdown 2. Hopefully this is making sense. If dropdown 1 doesn't change, dropdown 2 still has the same options from when the form was built in the code behind, so the value in the viewstate can be found when it's posted.
Right now, I have a hidden field to keep track of that value that was selected and works fine for now, but is a bit clumsy. Before I did this development, both dropdowns had the AutoPostback attribute turned on. That caused the form to get resubmitted without submitting the form, just so the dropdowns could get rebuilt.
Is there a better approach to this problem without making the button perform an AJAX call to submit the data?
Values manipulated in JavaScript can't be maintained on postback, because it won't be accessible on the server side. You can put the selected Value in the Hidden Field and then get it from the Hidden Field.

Call a JavaScript method after the RequiredFieldValidator fires?

Is it possible to fire a JavaScript method after a form element is considered invalid? Here is my scenario:
There are 2 tabs on the ASPX page. The user has to fill out info on both tabs. The user, while on tab 2 clicks the submit button. However, there is a required field on tab one that needs attention. Do I need to create a custom valuator (either a CustomValidator control or create a new control from the base valuator) to call a JavaScript function to display tab 1 and show where the error is?
Unfortunately, the canned Field Validator controls in ASP.NET Webforms are not very extensible. I've had needs to change the CSS class of an input field to an invalid state upon client-side validation, and I never found a good way to handle this.
I think your best bet might be to do your own client-side validation. I've also looked into this third party product and it seemed to be pretty fully-functional, but I couldn't justify the cost in my case: http://www.peterblum.com/DES/Home.aspx
You can call any js function from your server side code after the validation check on page object and inside the js function you can write the logic to highlight the field which has issue on validation:
if(!Page.IsValid)
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "validate", "myjsfunction();", true);
}
else
{
// type code here
}

Is it dangerous to store user-enterable text into a hidden form via javascript?

In my asp.net MVC application I am using in place editors to allow users to edit fields without having a standard form view. Unfortunately, since I am using Linq to Sql combined with my data mapping layer I cannot just update one field at a time and instead need to send all fields over at once.
So the solution I came up with was to store all my model fields into hidden fields, and provide span tags that contain the visible data (these span tags become editable due to my jquery plugin). When a user triggers a save of their edits of a field, jquery then takes their value and places it in the hidden form, and sends the whole form to the server to commit via ajax.
When the data goes into the hidden field originally (page load) and into the span tags the data is properly encoded, but upon the user changing the data in the contenteditable span field, I just run
$("#hiddenfield").val($("#spanfield").html();
Am I opening any holes this method? Obviously the server also properly encodes stuff prior to database entry.
Assuming your server is properly detecting and dealing with XSS attempts, there's no way a malicious user could submit an attack for another user. Unless someone wants to hack themselves(?), it seems secure to me.
I find this approach pretty unsavory. I guess the overall soundness of this scheme depends on what fields you're actually populating this way --
For example, if you store fields that are supposed to be set only once (at the time of record creation) and never changed, this will allow a (malicious) user to change the field values mid-stream by editing a hidden field before posting (very easy to do, for example, with Firebug).
There's no difference here than if you were providing visible input fields and having that form submitted. Simply shuffling the data into hidden fields vs. visible ones would not make a difference.

Categories