asp:upload postedfile lost during postback - asp.net

I am using an asp:upload control to upload an image and am using the postedfile property to insert the path to the database. In my form I have a dropdown with autopostback=true where the user can select a topic to populate a checkbox list of categories. During that postback, the postedfile value is being lost and after a little research I have discovered that the posted file value is not maintained in viewstate for security reasons. Has anybody else found out how to get around this?

That's how it works. The value of a intput type="file" is never used on parsing an HTML page. That's a huge security risk, so no modern browser will allow them to 'retain' values. So in ASP.NET, every postback "loses" the value.
On any postback with a file in the input control, be sure to save the value somewhere you can get to it later.
Or don't design a form that uses a file upload to have multiple postbacks. Perhaps consider wrapping your drop down list and associated control in an UpdatePanel so the file upload doesn't get cleared.

The value attribute of an input file element simply cannot be set by anything except user interaction. That's the way it works, and that will not change due to security concerns. That said, your solution is to eliminate the postback.

I would try to load the checkbox list via JavaScript/AJAX, possibly saving the values of the checkbox list to a hidden field so I can retain the values on a postback.
This may not be ideal, but if you want to do this all with no postbacks, at some point your going to have to use JavaScript.

You could try the AsynchFileUpload control in the AjaxControlToolkit, but there isn't a workaround for the standard fileupload unless you save the file to a temporary folder and load a file list from that temp folder.

Related

FileUpload in Autogenerate Form postback

I have a problem. I have a Dynamic form created in asp.net. Generally it has fileupload companent . In This time page postback is fire than form generated again and selected file is disappear. My question is how to hold this file in memory?
Am I hold this folder in fileselecting?
Have you any idea for this?
This is due to security in asp.net. You do not have the ability to specify the value of the file upload and a postback will clear it. You could take care of this by doing thing asynchronously. Try using the AsyncFileUpload control in the AjaxToolKit. You can read about how to use it at http://www.kruegerwebdesign.com/blog/async-file-uploading-using-asp-net.

How to Persist a Control's Value/Text Property Between Page Refreshes?

I have two controls of interest on a page: a DropDownList and a Button. If the user presses the button, he gets a popup form which, when completed, causes the base page to completely reload, losing the value in the DropDownList. To clarify, it's a refresh, not a postback. I cannot change it to make it a postback. What is the most straightforward way of persisting the selected value in the DropDownList across this page refresh? I cannot avoid the page refresh, because the data entered in the popup is reflected elsewhere on the base page.
Update
I've cobbled together a tenative solution that I'm not terribly happy with: when the user clicks the button, I use javascript to get the current value of the dropdown and pass that with the querystring to the popup being loaded. When the user clicks "Save" on the popup, which causes the data to be saved then the base page to be reloaded, I first store the querystring value into a Session variable. The base page, on loading, looks at said Session variable. If a value is present, it sets the value of the dropdown accordingly and deletes the Session variable.
Although somewhat kludgy, it's the best I can come up with. I know that my Gracious Benefactors dislike using Session variables, but given the page reload, I cannot come up with an alternative. Also, since the Session variable is short-lived, being created shortly before a page is closed then being deleted shortly after the succeeding page is opened, I'm hoping this will be acceptable.
Contrasting opinions, refutating my solution or reasoning, are enthusiastically welcome.
Conclusion
Ultimately, after I described the solution to my Gracious Benefactors, we agreed upon an alternate approach: if a selection is made in the DropDownList, it must be saved before opening the popup. This avoids the whole ViewState problem altogether.
For updated question:
The solution you are trying sounds like it should work. It's not the sort of thing you want to use SessionState for but there are requirements here that make the situation out of the ordinary.
Depending on how you are getting the base page to reload you may be able to add a query string to that which would save you from putting hte value in the SessionState. But I imagine you have probably considered that.
But basically, as Postback values and viewstate are out of the question, SessionState and query strings are you only real option. Oh, unless you are allowed to use HTML5 local storage? (probably not)
From before question update:
If the aspnetForm is being posted back the the value should be persisted automatically by means of the postback values. So the first thing to know is whther your form is going through a postback or if you are refreshing the page in some other way.
If you can't postback the main form then as rockinthesixstring said an Ajax post might be what you need.
Also, if you are doing anything fancy with binding the datasource to the DropDownList or trying to persist the selectedValue yourself then check and re-think that.

ASP.Net ListBox values not posting changes after jQuery manipulation?

I have an ASP.Net page with two ListBox components, rendered in the browser as <select> lists. I'm using jQuery to move elements from one list to another by manipulating the DOM. I then select all elements with the mouse and postback the form. That way, all the list elements are posted with the form.
When I submit the form, in my button_save() event handler, the Request.Form[<<listbox ID>>] values are correct. However the ListBox controls themselves, specifically their Items collections, do not reflect my changes.
I've also used Fiddler to modify the select items and submit the form. Same as above, the ListBox values are no different, though the Request.Form values are. Would anyone know what's going on or what incorrect assumptions I'm making?
I believe the problem is that the server constructs a ListBox object that is unaware of changes made to the select box on the client side. That is to say, it uses the ASP.NET markup to construct the list of items, rather than the information submitted from the request.
I'm not aware of any workaround to this, other than accessing the Request.Form values directly.
I believe the root issue is: the ListBox's options are stored in the page's viewstate. When you use client-side javascript / jquery to modify the list's contents, those changes are not reflected in the viewstate. Thus, when you postback, ASP.NET uses the viewstate to build the lists for your codebehind, and your client-side changes are lost.
One way to resolve this would be to manipulate the lists' content via postback, instead of client-side (javascript/jquery). By doing it that way, all changes to the listboxes are incorporated into the viewstate, and thus will remain consistent for each postback.
I am a big fan of jquery (much moreso than postbacks or MS-Ajax/partial-postbacks), so I completely understand that this approach may not be very appealing. Unfortunately, it's the only one I can think of right now. Maybe other stackoverflow'ers will have better alternatives.
Larry, in case you haven't found a solution, here is what I would do.
As other fellows stated, since you are changing DOM client-side, the changes are not reflected to ViewState and therefore you cannot access new values from code-behind.
As a solution, you can create a hidden value and set its value to a serialized form of the lists (combined value/text pairs) everytime you change a list with jQuery. Then you can access the hidden value from code behind and finally deserialize it to get all changes. The method is pretty straightforward actually.

Maintaining ViewState for FileUpload Control

I am creating FileUpload controls at run time. When I click a LinkButton a new FileUpload control is generated.
Now suppose I have selected a file from a FileUpload control and I click the LinkButton. The previous FileUpload control loses its path. However, I'm maintaining the ViewState of each control that I create at runtime by using this line:
f1.enableviewstate = true;
How do I maintain the selected file for a FileUpload control?
Steps
user selects a file
user click LinkButton (issues a postback that adds additional file uploading control)
server side should get the file on postback and store it somewhere (anywhere)
replace first <input type=file> with something like Label and check mark icon (to tell user the file has already been uploaded (or even a read-only text box with disabled browse button to fake file upload control - however you won't be able to display correct file path in it)
user is presented with a new form that has new empty file upload control in showing already uploaded files.
For security reasons you can't manipulate <input type=file> in any way shape or form.
Hack approach
If I understood you correctly your link button adds additional file upload controls to your page. Instead I'd create a sufficient number of upload controls the first time and display just one. Others would be hidden by CSS. After user clicks the LinkButton, it would however have only client-side Javascript functionality that would reveal additional control. And another... and another... and another... until maximum is reached.
Complex approach
You could however make it in a different way by using more Javascript and make it more Web 2.0-ish. You should however upload those files via <iframe>
as some of the others mentioned, you cannot preserve the viewstate of a FileUpload due to security issues.
What you could do is to simply add a Label just below the FileUpload. When the user clicks on the linkbutton in order to generate a new FileUpload, a postback will be fired where you could check whether the FileUpload controls present on the page have some value (i.e. the user already selected a file to upload), and if so, you could directly start to upload that file and show the result (the path or filename) on the label, just that the user knows he has added that file already. You could also hide the fileupload and additionally add a remove link to again remove the uploaded file (similar approach as Gmail does).
Hope this helped.
Juri
You can't pre-select a file path in the file upload input tag (security related - the user must select the file), so .Net is not able to populate the value from viewstate.
Consider if you really need to at it at runtime?
If you really need to at runtime; Don't forget to add it to the closest container's Controls property. Doing this makes sure it's state is serialized to the ViewState.
Hope this helps...
as per me there is no way to persist viewstate of fileupload in asps.net.
u can store it's value in hidden field,session etc file u can not be able to assign that value to again file upload because it is read only

ViewState or HiddenField

If I have a simple piece of data to store (an integer or string for example) I might choose to store that in ViewState, or using a HiddenField control.
Why would I choose one over the other?
ViewState
Hard for the user to decode (thought not impossible), which might be desirable
HiddenField
Value can be used in JavaScript
Are there other pros and cons?
Not really, ViewState is actually stored in a hidden field so the only real difference is the encoding.
Unless you need to manipulate the value with JavaScript or you hope to turn off ViewState on this page altogether then I'd use ViewState. Mostly just because there are third party tools (like this one) which understand ViewState and which won't understand your custom hidden field.
From a maintainability point of view, I'd use ViewState. It's less code for you to write, which comes down to fewer points of failure in your software. It also means that any developers coming after you will have an easier time maintaining your solution.
If you're not entirely comfortable with that, write a property accessor on the page that acts as a facade to retrieve the value from the ViewState. Later, if you feel compelled to convert it to a hidden field, the accessor can handle that switch seemlessly for the rest of the code. Just be sure you document your reasons for doing so.
Viewstate is only good on the page you are on or posting back to. With a hidden field you can access the data on the next page you navigate to (as well as other data) by using PreviousPage method of the Page object like so:
string term = ((TextBox)Page.PreviousPage.FindControl("txtSearchTerm")).Text;
The ViewState is stored in the page itself so it increases the page size and it may cause performance issues.
Also we can configure the application to save the viewstate on server rather than on page itself which might protect from some security issues.
Jomit
The hidden field are invisible on page and their values can be viewed in view source but the value of view-state are encoded and are not readable.
The hidden field value are posted on next page. (Note: use server.transfer to get the value of hidden fields).

Resources