ASP.NET MVC 2 Getting form values without postback - asp.net

I have an odd question that im not sure has been asked/answered, and im not sure if mvc can do this but:
I have a really massive page/controller which i have been able to code well enough. The user can edit information on this page and wont get it saved to the database unless they specifically say, save. However, there is a list at the bottom of this page that you can add/edit and delete elements. Adding and editing takes you to a different page, and before the page change happens, i want to save the form data to session memory, but i dont know how to access it outside a postback. Can MVC do this?

I do not believe this is possible. There is no way to interact with Session object outside of some form of postback.
You may want to architect your solution as such that you can mitigate the need to go to a different page and return.
The adding/editing portion of your form could instead be handled through asynchronous web POSTS independent of your main form. JQuery UI's dialog window and UI Tabs come in nicely for sophisticated forms that need CRUD capabilities to other components of your web application.

Related

Dynamic User Controls in asp.net

Hello I am trying to lear how to create Dynamic User Controls in asp.net.
I just know that this type of controls are created or loaded at run time.
Someone knows a good tutorial about this topic?
thanks in advance,
The best thing you can learn about dynamic controls in ASP.Net webforms is how to avoid them. Dynamic controls in asp.net are filled with pitfalls. I almost always recommend one of the following alternatives:
Place a reasonable fixed number of controls on the page, and then only show the ones you need.
Figure out the source for the dynamic controls and abstract it out to a datasource (array, ienumerable, list, etc) that you can bind to a repeater, even if it's just a call to Enumerable.Range().
Build a user control that outputs the html you want, bypassing the entire "controls" metaphor for this content.
If you really must work with dynamic controls, it's important to keep the stateless nature of http in mind, along with the asp.net page life cycle. Each adds it's own wrinkle to making dynamic controls work: the former that you need to create or recreate the controls every time you do a postback, and the latter that you need to do this before hitting the page load event - usually in page init or pre-init.
Typically what people are talking about here is the dynamic instantiation and addition of a control to a placeholder.
For example
Control ControlInstance = LoadControl("MyControl.ascx");
myPlaceholder.Controls.Add(ControlInstance);
The above instantiates MyControl.ascx and places it inside of a placeholder with id of myPlaceholder.
I agree with #Joel by knowing the page lifecycle, the stateless nature in mind etc it is possible to avoid the pitfalls. The main things to watch out for, which I have had to do, are:
Page_Init – initialise the controls that are on the page here as they were the last time you rendered the page. This is important as ViewState runs after Init and requires the same controls initalised the same way as the way they were previously rendered. You can load the control using the code from #Mitchel i.e.
Control ControlInstance = LoadControl("MyControl.ascx");
myPlaceholder.Controls.Add(ControlInstance);
Page_Load – Load the content of the controls in here as you would with any control that isn’t dynamically loaded. If you have kept a reference to them in your page_init they will therefore be available here.
Keeping to this structure I haven’t had too much difficulty as this is appears to be the way that ASP.NET was designed to work, even if all the samples on MSDN don’t do it this way. The biggest thing that you then have to watch is tracking what state the page was in in regard to the controls that you have had rendered.
In my case it was take the section number of the multipage survey and reload the questions from the database, so all I had to do was track the currently rendered section number which wasn’t difficult.
Having said all that if you are using dynamic controls just to show and hide different views of the same screen then I suggest you don’t use them. In this case I would much rather use either user controls (with the inappropriate ones hidden), placeholders to mark areas that aren’t to be rendered yet, or separate pages/views etc. as that way you keep the pages to a single responsibility which makes it easier to debug and/or get useful information from the user about which page they were on.
The Microsoft article is very good, but the best article that I have been read is in the bellow link:
https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx
If you are really interested in ASP.NET Web Forms dynamic controls, I recommend that you study the DotNetNuke CMS Portal. DotNetNuke is one of the best cases using dynamic controls as your core feature to build dynamic portals and pages using ASP.NET Portals. It is free for download in www.dotnetnuke.com.
I hope it helps

Multiple Forms in ASP.NET

I realize that ASP.NET is only designed to support a single form. What I am confused about is what is the appropriate method for coding multiple "forms" on a .NET page (I have a login form at the top of the page, via the Site.Master and other forms will appear on any given page). Am I supposed to respond differently? It doesn't really make a whole lot of sense. I would appreciate it if someone could clarify. Thanks.
P.S. I am currently developing on .NET 2.0 although I plan to move to .NET 3.5 soon.
Nearly all ASP.NET Web Forms post back to the same page. Unless you are working on some strange outlier (which your question doesn't indicate), you just use one form tag around the entire document, and use event hookups to your controls to handle the various instances.
For example, you can have three buttons that act as Submit buttons, one for each "form" but all inside that same form tag, and each one will call its respective event. This behavior is standard and handled by ASP.NET for you; all you have to do is write the event handlers and wire them up.
I'm not sure what you mean by a logon form. Are you doing some special ajax stuff?
You should be dividing any logical "form" as you call it into its own usercontrol.
http://www.asp101.com/lessons/usercontrols.asp
When dealing with aspx pages, think of the form on the page the same way you think of the body tag.
In that case, I would hand-code the login form at the top to submit to a separate login.aspx page. Leave the rest of the page to the other form's own purpose.
by default you can't, it's how the whole webforms technology works (MVC would probobly fix this in the newest versions).
So really it depends on what you want the "two forms" to do. For example, there's no issue with having login & search on one page, as each button has its own click event and go from there. If you wanted a second aspx page to process one of them, you could collect values and pass them through a response.redirect or some other hacky solution.

A big dilemma - ASP.NET and jQuery

I have a wizard style interface where I need to collect data from users. I've been asked by my managers that the information is to be collected in a step by step type process.
I've decided to have a page.aspx with each step of the process as a separate user control. step1.ascx step2.ascx etc...
The way it works now, is that when the initial GET request comes in, I render the entire page (which sits inside of a master page) and step1.ascx. When then next POST request comes in for step 2 (using query string step=2), I render only step2.ascx to the browser by overriding the Render(HtmlTextWriter) method and use jQuery html() method to replace the contents of a div.
The problem with this whole approach, besides being hacky (in my opinion) is that it's impossible to update viewstate as this is usually handled server side.
My workaround is to store the contents of step1.ascx into temporary session storage so if the user decides to click the Back button to go back one step, I can spit out the values that were stored for it previously.
I feel I'm putting on my techy hat on here in wanting to try the latest Javascript craze as jQuery with .NET has taken a lot of hack like approaches and reverse engineering to get right. Would it be easier to simply use an updatepanel and be done with it or is there a site with a comprehensive resource of using jQuery to do everything in ASP.NET?
Thanks for taking the time to read this.
Another approach, that might be easier to work with, is to load the entire form with the initial GET request, and then hide all sections except the first one. You then use jQuery to hide and show different parts of the form, and when the final section is shown the entire form is posted in one POST to the server. That way you can handle the input on the server just as if the data entry was done in one step by the user, and still get the step-by-step expreience on the client side.
You could just place all your user controls one after another and turn on the visibility of the current step's control and turn on other controls when appropriate . No need to mess with overriding Render(). This way the user controls' viewstate will be managed by the server. and you can focus on any step validation logic.
Using an UpdatePanel to contain the steps would give the ajax experience and still be able to provide validation on each step. If you are OK with validating multiple steps at once, Tomas Lycken's suggestion (hide/show with JQuery), would give a fast step by step experience.
Did you look into using the ASP.NET Wizard control? It's a bit of a challenge to customize the UI, but otherwise it's worked well for me in similar scenarios.

I have to integrate an existing asp.net web app into another page by using jQuery's load() method

I have to integrate an existing, simple asp.net web forms app including postbacks etc. into another external site with a jQuery load() call., an app that was intended to be integrated through an iframe. I doubt that's possible without a rewrite of the app.
The app is a basic questionnaire that leads the user to a product suggestion at the end.
Does anyone have any pointers to how I could solve this? I guess I will probably have to rewrite the app with web services and dynamic calls to RenderUserControls, I will also need access to the page that calls the load() and write additional jQuery methods to handle the user input... I will probably have to remove all of asp.net's postback calls and rewrite the handling of the user input?
First of all you should note that the load() function, like all ajax, can only work on the same domain. So if the 'external site' is on another domain ajax is the wrong choice.
It does sounds like a lot of hard work, depending on the complexity of the page. Postbacks can occur in many places - image clicks, combo selects, etc. Also, there are hidden fields to worry about, like the View State and Event handler - those have the same names on both pages. You'll have an easier time if the external site has no state and postbacks.
If the pages are relatively simple this can probably be done. It's been my experience that forms don't work well in other forms, so you'll have to remove one of them (probably the loaded page's form), or place them one after the other. As you've mentioned, you'll have to rewrite postbacks, you'll want to serialize the data. You may be able to change this string to fit the names on the original page (if you've changed the name of the viewstate, etc, it's easier to change it back on the serialized string than to mess with IDs), post it to the original page, and load again.
Personally, as much as I like jQuery, and as much as this project sounds interesting (and it is), I'd probably go for a server-side solution. It sounds much easier to create a user control (that may use ajax itself), or to the expose the page's functionality using web services or better, generic handlers.

Options for Dynamic content in ASP.Net

What choices do I have for creating stateful dynamic content in an ASP.Net web site?
Here's my scenario. I have a site that has multiple, nested content regions. The top level are actions tied to a functional area Catalog, Subscriptions, Settings.
When you click on the functional action, I want to dynamically add content specific to that action. For example, when Catalog is clicked, I want to display a tree with the catalog folders & files, and a region to the right for details.
When a user clicks on the tree, I want a context sensitive details to load in the details region (like properties or options to manage the files).
I started with UserControls. They worked fine as long as I kept loading everything into the page, and never let one disappear. As soon as one disappeared, ViewState for the page blew up because the view state tree was invalid.
(I didn't want to keep loading stuff into my page because I don't want the responses to be too huge)
So, my next approach was to replace my dynamic regions with IFrames. Then instead of instantiating a UserControl, I would just change the source on my IFrame. Since the contents of the IFrames were independent pages I didn't run into any ViewState problems.
But, I'm concerned that IFrames might be a bad design choice, but don't fully understand why. The site is not public, so search engines aren't a concern.
So, finally to my question.
What are my options for this scenario? If I choose an Ajax Solution (jQuery), will I have to maintain my own ViewState? Are there any other considerations I should take into account?
Controls that are added dynamically do not persist in viewstate, and this is the reason that it doesn't matter if you use AJAX or iframes or whatever.
One possible work-around is to re-populate controls on postback. The problem with this, is the page life-cycle (simplified) is:
Initialize
LoadViewState
Load Postback Data
Call control Load events
Call Load event
Call control events
Control PreRender
PreRender
SaveViewState
Unload
What this means is the only place to re-add your dynamic controls is Initialize -- otherwise posted data (or viewstate information) is not loaded into that control. But often, because Viewstat/postback data isn't available yet in Initialize, your code doesn't have the information it needs to figure out which controls need to be added.
The only other work-around I've found in this situation is to use a 3rd party control called DynamicControlsPlaceholder. This works quite well, and persists the control information in viewstate.
In your particular case, it doesn't seem like there are that many choices/cases. Is it practical just to have all the different sets of controls in the page, and put them inside of asp:placeholder controls, and then just set one to visible, depending on what is selected?
Some other options:
Content only appears to be dynamic. You load enough controls on the page to handle anything and only actually show what you need. This saves a lot of hassle messing with view state and such, but means your page has a bigger footprint.
Add controls to the page dynamically. You've already been playing with this, so you've seen some of the issues here. Just remember that the place to create your dynamic controls for postbacks is in the Page_Init() event, and that if you want them to be stateful, you need to keep that state somewhere. I recommend a database.
you've got a number of different options, and yes, IFrames were a bad design choice.
The first option is the AJAX solution. And with that there's not really a viewstate scenario, it's just you're passing data back and forth with the webserver, building the UI on the fly as needed.
The next option is to dynamically add the controls you need for a given post, everytime. The way this would work, is that at the start of the page life cycle, you'd need to rebuild the page exactly as it was sent out the last time, and then dump out all the unneeded controls, and build just those that want.
A third option would be to use Master pages. Your top level content could be on the Master page itself, and have links to various pages within the website.
I'm sure given enough time, I could come up with more, but these 3 appeared just from reading your problem.
dynamic controls and viewstate don't mix well, as noted above - but that is a Good Thing, because even if they did the viewstate for a complex dynamic page would get so bloated that performance would diminish to nil
use Ajax [I like AJAX PRO because it is very simple to use] and manage the page state yourself [in session, database tables, or whatever works for your scenario]. This will be a bit more complicated to get going, but the results will be efficient and responsive: each page can update only what needs to change, and you won't be blowing a giant viewstate string back and forth all the time

Resources