Assume you have a page in ASP.NET where it makes sense to use JavaScript/jQuery to modify the DOM with values that will eventually be read by the server on submit. For example, you have a form that allows end users to add/remove objects (like dependents on a health insurance form or assets on a loan application).
What are some ways to ensure that these items are detected and retrieved by the server once the information is submitted?
I've tried a few things that work, but none of them seem perfect so I wanted to see what the community had to offer.
Also, I'm not looking for suggestions that avoid dynamic DOM elements (like use a Wizard, etc.). I'm specifically trying to impro开发者_JAVA技巧ve my technique with dynamically created DOM elements.
There are two ways to do something like this:
First: post only the information on submit. As long as you add both a name
and an id
attribute to every element in your DOM, every element is represented in Request.Form
, so you can easily iterate through this collection.
I tend to have a naming convention like insurance_row_1
, insurance_row_2
and so forth. You can find all rows like Request.Form.AllKeys.Where(k=>k.StartsWith("insurance_row_"))
.
When you want to save every action on the server:
Maintain a state container in javascript, that holds information in some dictionary-like control, where you put every action that has been performed by your application, and a state whether the server has processed them. Something like:
var stateContainer = [
{ 'put-insurance-row-1', false },
{ 'delete-insurance-row-1', false }
];
Do an AJAX request to the server to perform such an action, and use the state-container's key to track whether the request succeeded or failed. Set the state to 'true' when the request has been successfully submitted. Make sure to do this in order in which you receive the events, so send them one-by-one to the server to ensure that you keep a valid state.
You can (try) to prevent closing the browser if some states aren't persisted yet.
why are you using client side code to do this? i would go the route of doing a postback and adding a control from server side code. the built in ajax updatepanel should handle this very quickly.
精彩评论