ASP form losing file attachments on postback - c#

I have an aspx form that contains a series of user inputs and then a submit button that packages that info and sends an email with the parsed data and any attachments.
I'm using an asp:fileupload for the user to attach files to the email, and on the button click it hits a method i wrote in the codebehind that checks to ensure all the required fields were populated, if it's not I kick back an error message popup and focus the first required field that fails. The problem is after the pushback it loses the attachment. So I need to be able to check my fields client side and my background is in C++ so scripting is new to me. Any help is appreciated.
part of my form for visual reference:
http://i.stack.imgur.com/Ioawg.png
showing how I'm doing error handling currently
http://i.stack.imgur.com/PhfQw.png

On postback, the uploadfile will clear; this cannot be prevented. But there are workarounds.
First, if possible, add RequiredValidators to check for missing data on the client side prior to submitting the form.
<asp:textbox id="Text1" text="Enter a value" runat="server" />
<asp:requiredfieldvalidator id="RequiredFieldValidator1" controltovalidate="Text1"
text="Required Field!" runat="server" />
<asp:button id="Button1" runat="server" text="Validate" />
<asp:validationsummary id="valSum" displaymode="BulletList" runat="server" headertext="You must enter a value in the following fields:" />
You could also write some javascript to do the auto-focus you are looking for.
If you really need to submit the form and validate it on the codebehind, save the posted file to a temporary folder on the server with a random file name. Update a hidden label or ViewState on the form with the file name so you can get the file back from the server on the next postback. You can hide the upload control and replace it with a label "File {name} ready for upload" and a button "upload different file".
Note: Do NOT put the actual file contents in viewState or session. That is not going to be good for performance.

When you first retrieve the contents of the file, persist them somewhere such as ViewState, Session, or database. Then you only need to receive the file once.
To avoid confusion, you can make retrieving the file and gathering the rest of the form inputs into separate steps in your workflow.

This is a security feature with the post back mechanism. The server can't retain any information regarding where the physical file gets stored. It only knows that you sent a series of bytes into a field.
One way around this is to use AJAX to persist the state in the browser. You may look at UpdatePanel or do a simple implementation yourself.

Related

How to redirect to another page after submit with asp.net c# DNN?

I've encountered a problem after I fire the submit button, the page redirect to itself. How do I redirect it to another page after submit?
My submit button also have C# code behind it where it uploads the files to the server, creates a folder and sends out an email.
I assume that server side form control (runat=server) is designed to post-back to self...
Probably a Response.Redirect("PageName.aspx") is what you are looking for.
Response.Redirect("http://...../Default.aspx", false);
Context.ApplicationInstance.CompleteRequest();
in order to void this
https://www.jasoft.org/Blog/post/solucionar-el-error-thread-was-being-aborted-en-asp-net
You can use PostBackUrl="~/Confirm.aspx"
For example:
In your .aspx file
<asp:Button ID="btnConfirm" runat="server" Text="Confirm"
PostBackUrl="~/Confirm.aspx" />
or in your .cs file
btnConfirm.PostBackUrl="~/Confirm.aspx"
https://stackoverflow.com/a/23976700/2067560

Fill server DropDown with javascript

Is it possible to add drop down items throught javascript, and then get it on server side?
I have
<asp:DropDownList ID="testDropDown" CssClass="listClass" runat="server"/>
<asp:Button ID="saveButton" runat="server" Text="Добавить" OnClick="saveButtonClick" />
After page load javascript add items to drop down
$('.listClass').append("<option value='value1'>Text1</option>");
But after saveButton click i have empty drop down on server
Any dynamic changes that happen on the client-side will not be automatically replicated on the server side.
You need to record the fact the action took place somehow (using, for instance an <asp:HiddenField> control)... then on the post-back, check for whether the action happened and replicate the value that took place on the client.
Also, be careful, as ASP.NET will probably throw an exception due to the fact that control is returning a value that ASP.NET did not populate the control with in the first place. To counteract this, either set the EnableEventValidation="false" in your <#Page> declaration, or add all possible values using Page.ClientScript.RegisterForEventValidation
You cannot do this in ASP.NET because the values are contructed using the ViewState on the server side.
Check this. It may be helpful for you: Options added to <select> by javascript lost in postback

How do I get the RadTextBox TextMode=Password to accept the Auto Filled value in the code behind?

Google Chrome and FireFox browsers have a feature that allows users to save user name and passwords to their local machine. This allows them to login the next time without much effort or remembering what that information is. The information is basically auto-filled. When those browsers do this it shows the * in the textbox. Showing that the browser successfully placed the value in the RadTextBox. However, when the c# code behind retrieves the value as an empty string.
My code is as follows
<telerik:RadTextBox ID="txtPassword" runat="server" ToolTip="Enter password"
Text="" MaxLength="40" EnableSingleInputRendering="False"
Wrap="False" TextMode="Password" CausesValidation="false" Skin="WebBlue">
</telerik:RadTextBox>
Code Behind:
objLogin.Password = txtPassword.Text;
Even odder is the fact that if you click the button more than once it will then the code behind will see the actual value and proceed to log you in. It seems that the RadTextBox Control needs to be rendered a second time or post back is required for the control to work properly.
What do I need to do to get the RadTextBox control to recognize the inputed value from the browser initially without having to click multiple times for the code behind to see the value?
Thanks for your help.
That is because your textboxes gets the value on the client side alone, while the underlying RadTextBoxes values do not.
I have experienced this issue before where values set to a RadTextBox by using jQuery xxx.val('...') do not get through to the server-side on postback.
The only way to get the value 'assigned' to the RadTextBox control's Text property from client-side is to use:
$find('<%= txtUsername.ClientID%>').set_value('newvalue');
In your case, most probably the browsers set (autofill) the values and only available on client side. Therefore, what you can do to actually assign those values is to intercept before the Login button postbacks, like so:
var un = $('#<%= txtUsername.ClientID%>').val();
var pw = $('#<%= txtPassword.ClientID%>').val();
$find('<%= txtUsername.ClientID%>').set_value(un);
$find('<%= txtPassword.ClientID%>').set_value(pw);
If you are using RadButton as the Login button, this can be done on the button's OnClientClicking/OnClientClicked event like so:
<telerik:RadButton ID="cmdSignin" runat="server" Text="Sign In"
SingleClick="true" SingleClickText="Signing In..."
OnClientClicking="OnClientClicking"></telerik:RadButton>
Hope that helps.

How can I make a RequiredFieldValidator trigger a message elsewhere on the page?

I have a page with a repeater containing RadioButtonLists which have requiredFieldValidators attached to them. I need to keep the RFV next to the control (it's the only way I can get it to work to be honest!)
However, the form is made up of a few sections contained in an accordion. This means that when the form is submitted, the item that has failed validation may not be visible, so the user won't know where the error is.
Is there a way I can also have a message by the submit button which is triggered by an RFV changing saying "please go back and check your answers" or something? I guess I'd need to use JQuery / JavaScript as it would be clientside.
There is a special ValidationSummary control for that:
<asp:ValidationSummary ID="Summary" runat="server"
DisplayMode="SingleParagraph"
HeaderText="Please go back and check your answers" />
This control is used to summarize all validation errors on the page.
Try "ValidationSummary". look for example from here.
http://www.w3schools.com/aspnet/control_validationsummary.asp

Pop Up Window Data Variable Passing

I am creating a web application for my company that needs to deal with form processing and database manipulation. The application is implemented using .NET Framework 3.5 using C# and Visual Studio 2008 as the IDE and Microsoft SQL Server 2005 as the database.
Here is my problem:
I have a lot of forms
But my boss only want me to create a single page for the database
processing (easier to extend in the future)
I figured out the only way to solve this problem is by having only 1 .aspx file (that contains everything about the database) and having it invoked as a pop up window everytime a forms need to deal with the database.
Here is another problem of mine:
Due to stateless nature of HTTP, I am unable to process and pass
variable between 2 different windows.
I managed to create certain Javascript functions and have the
variable transferred on display, however it can only pass a variable
that is the primary key in the table. To process other columns in
the table is possible but as the consequence I have to write a very
long inline script in my .aspx page and after it is compiled people
can easily view how to access my company database easily. Hence, I
don't favor this (beside to deal with 1 form, I need to create a
long code already, imagine if i have more than 1000 forms!)
So there are two ways you guys can help me:
Suggest another way other than popping up a new window for my
problem, maybe even advise on how it's implemented.
If you think popping up is the solution, you mind to share some
snippets that can help me figure out the variable passing between
two different windows. I can use some advise especially from some
Javascript expert on this :).
Note: Solution must be workable in ASP.NET Framework 3.5 and tested using IE browser version: 8.
P.S: This is a short explanation about my application flow
Let's say I entered data about a product (it has few properties id, name, price, etc) into the database
Later on somehow I want to edit one or few properties of that product, so I have to launch a form which called "editor.aspx"
Instead of entering the product id (which is the primary key) into the form (and edit the data based on the entered product id) and risking to miscalculately edit the correct data, I provide a small button in the form (let's name it btSearch), that will launch a new popup window which contains the gridview of the database of all product (with selection enabled)
Now I just need to browse through the gridview, select a particular row, it will close the popup and I expect to see few data from that row appeared on my original page (in the textboxes/labels)
I hope my explanation above clears the air, thank you.
I recently wrote something like that: A database handler as aspx file. But i invoked it by using ajax / jquery.
When my aspx file is done, i write something to the response stream, some code, a json string, what ever.
Example:
$.post("yourdatabasehandler.aspx", { name: "John", lastname: "Smith" }, function(data) {
alert("Response from page: " + data);
});
In that example, name and lastname are values that are posted to your site. You can access them like that:
string name = Request.Params["name"]
// Do your database , validation and whatever logic here
Response.Write("Cool dude");
The above javascript will alert "Cool dude" after your databasehandler is done. Inside your javascript you can react to the response how ever you want - For example reload a page.
Hope that helps? Regards
"1. Due to stateless nature of HTTP, I am unable to process and pass
variable between 2 different windows."
You very wrong with this comment to start with, trying MSDN and ASP.Net "How to pass values between ASP.Net Web pages". Passing between Windows only requires a little bit more thought and possibly a little Javascript to refresh a parent windows or cause a postback on a shild window etc.
If you're using a popup window, you can always use QueryStrings to pass a value going to your popup.
window.open("popup_page.aspx?id=" + id + "&name=" + name)
to access it in popup_page.aspx
string sID = Request.QueryString("id");
string sName = Request.QueryString("name");
Update: if you're using IE the this might help you.
function ShowPopup(strMessage)
{
var returnValue= window.showModalDialog("popup_page.aspx");
}
popup_page.aspx
<asp:Button ID="btnReturnValue" runat="server" Text="Proceed" OnClientClick="window.returnValue='some message';window.close();" />
Note: Please note this only works in IE, so I suggest consider using the followings instead:
jQuery
AjaxControlToolkit ModalPopup
I personally suggest the use of jQuery. :)
Thank's for all answers, comments. rates, and feedback. Just now I found a very helpful link here. Basically the answer is based on that particular code. I just need to alter some part.
<script language="javascript">
function GetRowValue(val)
{
window.opener.document.getElementById("ctl00_ContentPlaceHolder1_TextBox2").value = val;
// make sure you change the TextBoxId as respective to your creation
window.close();
}
</script>
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
<Columns>
<!-- Reserve the code below, as after you configure data source you -->
<!-- will alter this code drastically therefore-->
<!--you have to make sure to paste this code -->
<!-- again inside this Gridview element once you configure your data source -->
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" />
</ItemTemplate>
</asp:TemplateField>
<!-- This part must be reserved -->
</Columns>
Also remember to specify the connection string and the sql command in the datasource.
The rest just follow that tutorial and copy paste the code entirely.

Categories

Resources