Applying [ViewStateModeById] functionality to standard, dynamic ASP.net controls - c#

I'm new to ASP.net, the ViewState, and C# in general.
I have some code that adds and deletes boolean constraints that will later be submitted as an SQL query. I dynamically create these constraints with unique IDs. When I delete a constraint earlier that was added before some other constraint, the viewstate tries to map the contents of the DropDownList that was deleted to the DropDownList immediately below it.
This is turn triggers an index changed event and causes undesirable behavior in the application. I'm fairly certain that this behavior is caused because the ViewState loads the postback data into dynamically created controls via index.
I've been searching for a solution came across [ViewStateModeById] as a possible solution. Unfortunately, this seems to only to custom controls. I would like to avoid creating new custom controls for everything just to index the controls by ID.
Is there a way to gain this functionality without having creating custom controls?
I should mention that each dynamically generated constraint (which is a set of about 5 controls) is inside a dynamically generated panel. I could just keep creating empty panels as a sort of placeholder to get my desired behavior, but that is just a hack. I'll end up with many, many panels unless I implement another hack to occasionally delete some of my panels.

I struggled with the viewstate until I got it. This is not a real answer but when working with viewstate it is very important that the dynamic controls created gets the exact same id after each post back. It means that you'll have to re-create/re-bind everything on each post pack.
If it does I'd be surprised if you get strange behaviors and you should be able to code almost like if it was a desktop app.

Dynamically adding web controls to the page's control tree and later deleting some of them seems a bit strange to me.
But anyway, if you want to get rid of already existing controls in the control tree, you could just set their Visible property to false. Controls having Visible==false are not rendered to the client and thus behave almost like they wouldn't exist at all.
Or, what about creating them dynamically without immedialetly adding them to an actual control tree?
You could e.g. add and remove references to and from the Context.Items collection at any time during the page request and finally add just the ones you need.

Related

How to restore dynamically created HTML table/controls on Page refresh?

In my webpage, I am creating HTML table/div/controls at run-time. But, on Page refresh, it disappears.. What is the best way to retain/restore all the dynamically created HTML controls with their values?
ASP.NET and code behind is C#. Mostly I am using HTML controls, JQuery/JavaScript
All controls must be rebuilt in Page_Load so that event handlers and value binding can occur. So, if you create the controls initially in an event handler then you need to cache enough data in Session, or ViewState, so that you can rebuild those controls on Page_Load.
A lot of times a basic Tuple will work to provide enough information for those controls to be recreated. A little note though. You're going to need to ensure you set the ID property the first time they are built and when they are rebuilt. That's how value binding occurs.

Creating Repeater Template at runtime and based upon user input

Is it possible to dynamically create an ItemTemplate for a repeater somehow?
I am trying to use a repeater since it allows the most control, but one of my requirements is making me reconsider.
I basically have a number of SQL queries that I do through a web service. Rather than having users type in the entire query I want them to be able to select "parts", "products", or "packages" via radio buttons, enter a search term in a text box, and some other info, and the page returns the results they want. I have this mostly done, the RadioButtons control logic, and I have the query set up to accept the input from the text box as a search term with wildcards. The only probelm is I am struggling with the repeater control. The problem is each one of the tables has a different number of columns and they have different names, so doing a
<td><%# DataBinder.Eval(Container,\"DataItem.Description\") %></td>
within the ItemTemplate is not possible(I don't know until bind time which one of the 3(possibly more in the future)templates to use)
I tried using a literal to pass in what I wanted based on logic in the codebehind, but I couldn't pass the inline functions, and I have been unable to put together how to do this based on an earlier question.
I have been reading the MSDN reference and it seems like if I learn the DataList control it will make things easier, but I'd rather not waste time on that if there's an easy way to do it with a repeater(which will also allow me more control)
Thank you
I may be off track here but I think an easy solution to the problem you're having would be to create multiple repeater controls with different items templates inside them and wrap them up in panels. That way depending on the user parameters you could simply databind your result to the proper repeater and set the other panels to invisible.
I was looking back through some old code for you to see how I've handled similar situations. Then I saw Jesse's answer right before I wrote my reply. Basically, I would tend to agree with Jesse there - that seems the most straightforward solution from what you've outlined.
So I don't know how much this helps, but one possibility would be to use MVC Templates. MVC is handy in that it can actually be used in a very limited sense (your entire app doesn't need to implement it, just the applicable page) and it's also pretty straightforward.
An introduction on how to do different templates within MVC: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html
It might be possible to modify the template so that it changes based on the object that it's bound to - like how a WPF DataTemplateSelector works.
I thought I remember seeing something in MVC3 or MVC4 that you could create a Template based on a datatype (like you can in Silverlight) and it would automatically pick that Template, but I'm having trouble finding that now.

In ASP.NET, what's a good strategy for maintaining dynamically generated controls across Postbacks?

Although this is a great article on handling dynamic controls in ASP.NET, I have an application where I cannot generate controls on PageLoad or PageInit. They are generated much later, after the user has input data. Is there a good strategy for maintaining dynamically generated controls when I cannot generate them during PageLoad or PageInit?
Page_Load will still fire "after the user has has input data". ASP.Net is stateless and the page is regenerated every time there is a postback. In order for controls to keep their states properly you need to make sure you recreate them again.
Your Page_Load event is still firing. You can assign the controls an ID so they can be properly re-created on postback. If you do not assign controls an ID, they will get an automatically generated name. This will cause the input values to be lost and also the viewstate will not work properly.
I asked a similar question that might be of help to you.
Dynamic User Controls get and maintain values after postbacks

Strange behavior in ASP.net regarding WebControl vs UserControl ViewState

Ok, I've solved my problem but I don't know why one type of control works and another doesn't.
The scenario: I'm working on a custom wizard style page design that was originally done completely with UserControls in C# ASP.Net 4.0. The step that you are viewing is controlled on server side via control visibilty.
My problem: I dislike the UserControls and want to use WebControls as much as possible, though it's not worth my effort to redo the entire thing with WebControls, and new controls are needed to expand the functionality.
My original solution: I initially started creating WebControls as needed. This worked fine until I got 2 steps away from a given WebControl, where it lost it's ViewState. At least I believe that is what happened. It was a CheckBoxList and as soon as I was 2 steps away, the ListItems disappeared.
The final solution: Recreating the same control as a UserControl I always have access to the CheckBoxList Items.
This all seems fairly logical. If a control or one of it's parent's is not visible, it won't be included in the ViewState data. I guess the real question is, why does UserControl work?

Dynamically creating asp.net with c# pages

I am struggling with finding clear answers to dynamically creating the same page over and over. The questions and samples I have found seem to be all over the board on this topic. I have studied the life cycle and still seem to not have a clear answer as to where code should go.
I have a master page and a content page. All the content in the content area needs to be dynamically created (text boxes, ddl's, page tabs, buttons/onclick etc.).
After a user fills in data and clicks a submit button, I need to read the values off the form and rebuild the page completely again (not add/remove controls to current content).
My question is then.
Where do I put my code to build the page?
Will this area allow me to use IsPostBack so I can rebuild content with Request.Form values?
Will my buttons _Click events work?
Are there any working samples out there you could direct me to?
Thank you very much for the feedback...
I don't know all the answers to your questions, but I hope this may get you started. When dynamically generating the UI through code, this happens in Init. Controls dynamically loaded on Init is key because between init and load, on postback, viewstate is loaded for these controls.
This means you need, on every postback, recreate the page as is to match the previous control tree, then deconstruct it after init and recreate the new UI, if something is supposed to change UI wise. This is because it validates the tree structure to determine its the same UI. Now, if you don't need viewstate, this may not be as much of an issue. I haven't verified this without viewstate to see if it behaves different.
It depends how dynamic you need it, whether you need viewstate (is a big factor).
HTH.
Try creating the controls in the page's PreInit method. "IsPostBack" should work and the click event handlers should work as well.
What you need is a web user control, see ASP.NET User Controls
Brian's advices are good and you should follow them.
This might not really answer your question but still I add it as an advice. I'm professionally creating ASP.net web applications at quite a large scale and from my experience I can say that too much "dynamics" is usually bad and should be avoided because it just introduces complexity. Normally you might want to expose UI parts into ASP.net UserControls or if you want to make them even more reusable (if that's a factor) then into ASP.net Server controls. Then you replace different of them dynamically rather than creating everything from scratch.

Categories