How to retain Textbox values after a Postback? - c#

I have few Textbox, FileUpload and button controls within the same page. I had tried enabling the EnableViewState to True but it is still not working. The Textbox will lose its value when clicking the button to upload attachments. May I know what's wrong here, should I use ViewState to retain the values of the textboxes?
<div class="form-row">
<div class="form-group col-md-6" >
<asp:Label ID="lblConfiguration" runat="server" Text="Configuration*"></asp:Label>
<asp:TextBox ID="txtConfiguration" runat="server" type="text" class="form-control" EnableViewState="true" ViewStateMode="Enabled" ></asp:TextBox>
</div>
<div class="form-group col-md-12">
<div class="col-md-6">
<asp:FileUpload ID="fuUpload" runat="server" CssClass="nv-file-select uploader" multiple="true" />
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" CssClass="btn btn-secondary" />
</div>
</div>

Possible reasons
1) You have disable the Viewstate on full page - Check on top of aspx page if its enable or not
<%# Control Language="C#" AutoEventWireup="true" CodeFile="FileName.ascx.cs" EnableViewState="true" %>
2) At some point on code behind you change the value on post back - so check to not change it by adding this check
if (!Page.IsPostBack)
{
TextBox.Text = "";
}
3) For some reason after your post back you do redirect on same page.
4) For some reason you do not make post back, but reload

Related

Continuous postback

I can't figure out why my page keeps on refreshing, then I put a breakpoint on my Page_Load on aspx page. It keeps on refreshing and loading the Page_Load without me doing anything.
I have some textboxes that has AutoPostBack="True" for TextChange event. Do you guys think that is the problem? Do you guys have any idea why it keeps on doing POST?
Thank you, guys.
These are some of the code.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="VesselSchedule.aspx.cs" Inherits="VesselHeader.VesselSchedule" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Panel runat="server" DefaultButton="btnVesselCode">
<label class="col-sm-4 control-label">Vessel Code</label>
<div class="col-sm-4">
<asp:TextBox ID="txtVesselCode" runat="server" class="form-control pull-left" placeholder="Vessel Code" onkeypress="return EnterEvent(event)" AutoPostBack="True" OnTextChanged="txtVesselCode_TextChanged" />
<asp:Label ID="lblDescription" runat="server" Text="" ForeColor="blue" Visible="true"></asp:Label>
<asp:Button ID="btnVesselCode" runat="server" Text="Button" visible="false" OnClick="btnVesselCode_Click"/>
</div>
</asp:Panel>
<div class="col-sm-4">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<asp:TextBox ID="txtPublishedETADate" runat="server" ClientIDMode="Static" class="form-control" OnTextChanged="txtPublishedETADate_TextChanged" AutoPostBack="True"/>
</div>
</div>
Any kind of PostBack will fire the Page_Load event.
To not run the entire code in Page_Load on each post back you need to wrap your code inside a check. A simple if condition will do it for you.
if (!Page.IsPostBack)
{
//code to execute on fresh page load only.
}

Stop page refresh after button click

It is not a repeat post, I have already checked all the answers present on net and nothing is working for me so i'm posting this here.
Please find the code.
<form runat="server">
<div class="card">
<ul class="nav nav-tabs Main-Menu" role="tablist">
<li role="presentation" class="active">Check Box - Enabled</li>
<li role="presentation">Check Box - Disabled</li>
</ul>
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="Enabled">
<asp:CheckBoxList runat="server" ID="CheckBoxEnabled" RepeatDirection="Horizontal">
<asp:ListItem Text="Selenium IDE"></asp:ListItem>
<asp:ListItem Text="Selenium RC"></asp:ListItem>
</asp:CheckBoxList>
<asp:Button runat="server" Text="Submit" CssClass="btn btn-success Elements-Text" OnClick="btnEnabled_Click" />
<asp:Label runat="server" ID="lblEnabled" CssClass="label success"></asp:Label>
</div>
<div role="tabpanel" class="tab-pane" id="Disabled">
<asp:CheckBoxList runat="server" ID="CheckBoxDisbled" RepeatDirection="Horizontal" CellPadding="5" CellSpacing="5" CssClass="element form-control">
<asp:ListItem Text="Selenium IDE"></asp:ListItem>
<asp:ListItem Text="Selenium RC" Enabled="false"></asp:ListItem>
<asp:ListItem Text="Selenium WebDriver"></asp:ListItem>
<asp:ListItem Text="Selenium Grid" Enabled="false"></asp:ListItem>
</asp:CheckBoxList>
<asp:Button runat="server" ID="btnDisabled" Text="Submit" CssClass="element btn btn-success" OnClick="btnDisabled_Click" />
<asp:Label runat="server" ID="lblDisabled" CssClass="label success"></asp:Label>
</div>
</div>
</div>
</form>
I'm having 2 tabs in my page, when i'm on the second tab, select one checkbox and click on the button with #btnDisabled the page gets postback and navigates to the first tab. I want this to stop.
I have already tried,
1. AutoPostBack = false
2. onClick = "return false;"
but not able to solve the issues.
Any help will be appreciated. :)
You can save the index of active panel in a hidden control and use it after post back.
<input type="hidden" runat="server" id="tabIndex" value="0" />
I do not know how you switch between your tabs, but on each tab change you must save it's index in hidden field(by javascript). For example if you select the second tab, value of hidden field must change to 1.
Finally add this script after all of your tabs.
var tabIndex = $('#tabIndex').val();
$('.tab-pane').removeClass('active');
$('.tab-pane').eq(tabIndex).addClass('active');
You want to do btnDisabled_Click, but not refresh the whole page.
You need Ajax controls around the button or anything needs to be updated. Check the tool list to find it.
( Firstly download and install AjaxControlToolkit if you haven't.)

Two separate search forms on page are requiring each other's fields to be filled out on validation

I have a page that has two separate search forms, one for searching by item ID and one for searching by keywords. It looks like this:
I started with just the top one, I am now adding the bottom one. The bottom one is basically a copy and paste of the first one (both are components in Sitecore). This is the code for each:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="SearchByItemNumber.ascx.cs" Inherits="Bayer.CropScience.SC.Internet.US.Website.layouts.Bayer_CropScience.Scope.Country_United_States_Internet.RewardsCatalog.SearchByItemNumber" %>
<div class="form search-item">
<div class="clearfix">
<h3>
<label class="searchByItemNumber" for="item-num">Know your item number?</label></h3>
<div class="input-wrapper search-by-itemnumber-length">
<asp:TextBox runat="server" ID="txtSearchItemNumber" CssClass="search-by-itemnumber-length" placeholder="Search by Item Number" />
<asp:RequiredFieldValidator runat="server" ID="rfvSearchItemNumber" ControlToValidate="txtSearchItemNumber" ValidationGroup="searchCatalog" ErrorMessage="Please fill out this field." CssClass="error"></asp:RequiredFieldValidator>
</div>
<asp:Button runat="server" Text="Go" CssClass="small" OnClick="Search" ValidationGroup="searchCatalog" />
</div>
</div>
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="SearchByDescription.ascx.cs" Inherits="Bayer.CropScience.SC.Internet.US.Website.layouts.Bayer_CropScience.Scope.Country_United_States_Internet.RewardsCatalog.SearchByDescription" %>
<div class="form search-item">
<div class="clearfix">
<h3>
<label class="searchByKeywords" for="item-keywords">Search by keywords</label></h3>
<div class="input-wrapper search-by-keywords">
<asp:TextBox runat="server" ID="txtSearchKeyword" CssClass="search-by-keywords" placeholder="Search by keywords" />
<asp:RequiredFieldValidator runat="server" ID="rfvSearchKeyword" ControlToValidate="txtSearchKeyword" ValidationGroup="searchCatalogKeywords" ErrorMessage="Please fill out this field." CssClass="error"></asp:RequiredFieldValidator>
</div>
<asp:Button runat="server" Text="Go" CssClass="small" OnClick="KeywordSearch" ValidationGroup="searchCatalogKeywords" />
</div>
</div>
The problem is that when I fill out an item number and click Go, I get the validation error message "Please fill out this field" under the keywords box, and vice versa. How do I stop this from happening?
EDIT - The validation error occurs when I press "enter" but NOT when I click the "Go" button
EDIT 2 - It was a javascript issue, pressing enter was causing both fields to validate. I overrode it with a custom onkeypress function
You need to have different ValidationGroups. You're using ValidationGroup="searchCatalog" on all fields.
Assign a Unique ValidationGroup to fields that you want to be validated together.

Button event doesn't fire inside Update panel for FileUpload

I have a asp.net web form Page which uses master page also.
This is a simple page which displays some text and has a form, this page also allows user to upload resume in .doc, .docx & pdf format.
Problem with this code is that i am not able to trigger
for some reason <asp:Button ID="btnUploadCV" runat="server" Text="Upload" CssClass="btnUpload" onclick="btnUploadCV_Click"/>
<%# Page Title="" Language="C#" MasterPageFile="~/en/SiteMasterPage.master" AutoEventWireup="true" CodeFile="career.aspx.cs" Inherits="career" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<!-- Content Page-->
<!-- page content wrapper -->
<div id="page-content-area" class="page-content-area">
<div id="pg-left-bar" class="pg-left-bar">
<div class="page-title">
<h5><asp:Label ID="lblPageTitle" CssClass="page-title-lbl" runat="server" Text="Introduction"></asp:Label></h5>
</div>
<div class="page-text">
<asp:Label ID="lblPageContents" runat="server" Text=""></asp:Label>
</div>
<div class="career-form-wrapper">
<!-- UpdatePanel -->
<asp:UpdatePanel ID="updPnlArticles" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlCareerForm" runat="server">
<div class="row-form">
<div class="row-lbl-wrapper"> <span class="row-req">*</span>
<asp:Label ID="lblFirstName" runat="server" CssClass="row-label" Text="First Name:"></asp:Label>
</div>
<asp:TextBox ID="txtFirstName" runat="server" CssClass="row-input"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfFN" runat="server" ValidationGroup="Careers" ErrorMessage="*" CssClass="row-validate" ControlToValidate="txtFirstName"></asp:RequiredFieldValidator>
</div>
<div class="row-form">
<div class="row-lbl-wrapper"> <span class="row-req">*</span>
<asp:Label ID="lblFamilyName" runat="server" CssClass="row-label" Text="Family Name:"></asp:Label>
</div>
<asp:TextBox ID="txtFamilyName" runat="server" CssClass="row-input"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfLN" runat="server" ValidationGroup="Careers" ErrorMessage="*" CssClass="row-validate" ControlToValidate="txtFamilyName"></asp:RequiredFieldValidator>
</div>
<div class="row-form">
<div class="row-lbl-wrapper"> <span class="row-req">*</span>
<asp:Label ID="lblEmail" runat="server" CssClass="row-label" Text="Email:"></asp:Label>
</div>
<asp:TextBox ID="txtEmail" runat="server" CssClass="row-input"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEmail" runat="server" ValidationGroup="Careers" ErrorMessage="*" CssClass="row-validate" ControlToValidate="txtEmail"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revEmail" runat="server" ErrorMessage="*" CssClass="row-validate" ControlToValidate="txtEmail" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ValidationGroup="Careers"></asp:RegularExpressionValidator>
</div>
<div class="row-form">
<div class="row-lbl-wrapper">
<asp:Label ID="lblPhone" runat="server" CssClass="row-label" Text="Phone Number:"></asp:Label>
</div>
<asp:TextBox ID="txtPhone" runat="server" CssClass="row-phone" Text=""></asp:TextBox>
<asp:RegularExpressionValidator ID="revPhone" runat="server" ErrorMessage="*" ValidationGroup="Careers" ControlToValidate="txtPhone" ValidationExpression="^([\+]?[0-9]{1,3}[\s.-][0-9]{1,12})([\s.-]?[0-9]{1,4}?)$"></asp:RegularExpressionValidator>
<div class="tooltip tooltip-override" title="Accepts local format (eg. 04 1234567, 050 1234567 or 04-1234567, 050-1234657)<br />and international format (eg. +971 41234567, +971-41234567 ).<br />Also accepts an optional extention of up to four digits (eg. 04 1234567 289 or +974 41234567 289)">
<asp:Image ID="imgtooltip" CssClass="tooltip-img" runat="server" ImageUrl="~/images/tooltipgreen.png" />
</div>
</div>
<div class="row-form">
<div class="row-lbl-wrapper">
<asp:Label ID="lblFax" runat="server" CssClass="row-label" Text="Fax Number:"></asp:Label>
</div>
<asp:TextBox ID="txtFax" runat="server" CssClass="row-input"></asp:TextBox>
<asp:RegularExpressionValidator ID="revFax" runat="server" ErrorMessage="*" ValidationGroup="Careers" ControlToValidate="txtFax" ValidationExpression="^([\+]?[0-9]{1,3}[\s.-][0-9]{1,12})$"></asp:RegularExpressionValidator>
<div class="tooltip tooltip-override" title="Accepts local format (eg. 04 1234567 or 040-1234567)<br />and international format (eg. +974 41234567 or +974-41234567)">
<asp:Image ID="Image1" CssClass="tooltip-img" runat="server" ImageUrl="~/images/tooltipgreen.png" />
</div>
</div>
<div class="row-form">
<div class="row-lbl-wrapper">
<asp:Label ID="lblAddress" runat="server" CssClass="row-label" Text="Address:"></asp:Label>
</div>
<asp:TextBox ID="txtAddress" runat="server" CssClass="row-input-multiline" TextMode="MultiLine"></asp:TextBox>
</div>
<div class="row-form">
<div class="row-lbl-wrapper"> <span class="row-req">*</span>
<asp:Label ID="lblCountry" runat="server" CssClass="row-label" Text="Country:"></asp:Label>
</div>
<asp:DropDownList ID="ddCountry" runat="server" CssClass="row-dd"></asp:DropDownList>
<asp:CascadingDropDown ID="csdCountry" runat="server" Category="Country" TargetControlID="ddCountry" PromptText="-- Select --" LoadingText="[Loading Countries...]" ServiceMethod="FetchCountries" ServicePath="~/wsCountryCity.asmx" PromptValue="0"></asp:CascadingDropDown>
<asp:RequiredFieldValidator ID="rfCountry" ValidationGroup="Careers" ControlToValidate="ddCountry" CssClass="row-validate" InitialValue="0" runat="server" ErrorMessage="*"></asp:RequiredFieldValidator>
</div>
<div class="row-form">
<div class="row-lbl-wrapper">
<asp:Label ID="lblCity" runat="server" CssClass="row-label" Text="City:"></asp:Label>
</div>
<asp:DropDownList ID="ddCity" runat="server" CssClass="row-dd"></asp:DropDownList>
<asp:CascadingDropDown ID="csdCity" runat="server" Category="City" TargetControlID="ddCity" ParentControlID="ddCountry" PromptText="-- Select --" LoadingText="[Loading Cities...]" ServiceMethod="FetchCities" ServicePath="~/wsCountryCity.asmx" PromptValue="0"></asp:CascadingDropDown>
</div>
<div class="row-form">
<div class="row-lbl-wrapper"> <span class="row-req">*</span>
<asp:Label ID="Label1" runat="server" CssClass="row-label" Text="CV:"></asp:Label>
</div>
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="fileUpload" />
<div id="dFileUpload1" class="btnUploadHack">Browse</div>
<asp:Button ID="btnUploadCV" runat="server" Text="Upload" CssClass="btnUpload" onclick="btnUploadCV_Click" />
<asp:RequiredFieldValidator ID="rfvF1" runat="server" ValidationGroup="Careers" ErrorMessage="*" CssClass="row-validate" ControlToValidate="FileUpload1"></asp:RequiredFieldValidator>
<asp:Label ID="lblImageMSG" runat="server" Text=""></asp:Label>
</div>
<div class="contactus-row">
<asp:Button ID="btnSave" runat="server" CssClass="btnContactUsSave" Text="Send Message" onclick="btnSave_Click" ValidationGroup="Careers" />
</div>
</asp:Panel>
<asp:Panel ID="pnlCareerMSG" runat="server"></asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<!-- UpdatePanel -->
</div>
</div>
<div class="pg-right-bar">
<asp:Image ID="imgSideBanner" runat="server" />
</div>
</div>
<!-- page content wrapper -->
<!-- Content Page-->
</asp:Content>
Code Behind
protected void btnUploadCV_Click(object sender, EventArgs e)
{
// code is here
}
So far i am not able to figure out what i s blocking the any button inside from firing. Yes i did even put a simple button to test even that didn't fire.
I am not sure if it is Validation or Update Panel which is creating problem.
I tried using Trigger that didnt work
I tried setting
<asp:Button ID="btnUploadCV" runat="server" Text="Upload" CssClass="btnUpload" onclick="btnUploadCV_Click" CausesValidation="false" />
protected void btnUploadCV_Click(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid == true)
{
// your code here
}
}
My problem is it deosn't even enter code block of button for some reason.
Just to add further i am using cascading dropdown for country and cities i am not sure if that is causing any problem I am also using two panels one has the form control and after successful submission i hide this panel & show the other panel with success message all this code with UpdatePanel.
Only way out of this i see is to upload all files main form button Send Message rather than having individual button for all file upload control
UPDATE: I also tried this approach even this doesn't work
Please understand the concept
Update Panel is used for partial post back which is today we call AJAX
However AJAX cannot be used to upload file to the server
AJAX uses xmlHttpRequest which do not support file upload.
So, don't think that its a bug from Microsoft. Even today also, we don't have any javascript library which will support FileUpload using AJAX. All AJAX fileuploaders that you find on internet are using Flash :)
This is the limitation of protocol. Use any other jquery plugin to upload file. Update panel will not work for this.
FileUpload control doesn't work with asynchronous postbacks.To make this work in your application, follow below steps
1.) Place a <asp:ScriptManager /> on the page.
if you are using master page in your application and your web page uses the master page, place script manager in master page. If you don't want master page to have script manager,you can also place script manager on specific web pages anyways.
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
2.) After this, Add <Triggers> for the button btnUploadCV in your Update panel.
<Triggers>
<asp:PostBackTrigger ControlID="btnUploadCV" />
</Triggers>
And rest of your upload button OnClick handler looks like:
protected void btnUploadCV_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
fileName = FileUpload1.FileName;
FileUpload1.SaveAs("~/UploadedData/" + fileName);
...
}
}

ASP.NET AJAX Modal Popup - Dynamic Control Values

I am working on adding a modal popup to ASP.NET pages. The popup will give the user some textboxes to fill in, with a Cancel and Submit button.
The issue I'm running into is that the textboxes are being created dynamically, as the number of textboxes needed and what they are asking for will change depending on what is clicked on the page. When attempting to retrieve the values that have been entered after clicking Submit on the modal window (which is not tied to the modal window so that it will do a postback), the textboxes are gone by that point and the data cannot be retrieved.
Here's the code for the modal popup:
<div id="divModalContainer">
<div id="PromptContentHeader">
<asp:Label ID="lblHeader1" runat="server">
</asp:Label>
<br />
<asp:Label ID="lblHeader2" runat="server">
</asp:Label>
<asp:Label ID="lblPassFileName" runat="server">
</asp:Label>
</div>
<!--<ul id="ulTabModalPrompt" class="tabnav" runat="server">
</ul>-->
<div id="divModalPrompts" runat="server">
<table id="PromptTable" runat="server">
</table>
</div>
<div id="divModalButtons" style="width:230px;">
<div style="float:left">
<asp:Button ID="btnCancelDocPrompts" runat="server" Text="Cancel" OnClick="btnCancelDocPrompts_Click" />
</div>
<div style="float:right">
<asp:Button ID="btnSubmitDocPrompts" runat="server" Text="Submit" OnClick="btnSubmitDocPrompts_Click" />
</div>
</div>
</div>
</asp:Panel>
<ajaxtoolkit:ModalPopupExtender ID="modalDocPrompt" runat="server"
TargetControlID="btnOpenPromptWindow"
PopupControlID="panelPrompts"
OkControlID="btnHiddenOkButton"
CancelControlID="btnCancelDocPrompts"
BackgroundCssClass="ModalPromptBackground"
DropShadow="true" />
<asp:Button ID="btnOpenPromptWindow" runat="server" Text="Test Modal" Style="display: none;" />
<asp:Button ID="btnHiddenOkButton" runat="server" Text="Test Modal" Style="display: none;" />
Before the modal popup is shown, rows will be added to PromptTable, with a label and textbox in each row.
The btnSubmitDocPrompts_Click method will attempt to go through each row in PromptTable and retrieve the values entered, but once Submit is clicked, there are no rows anymore.
Thanks for the help!
You could try using JavaScript to write the values of the textboxes to a HiddenField (which will get posted back if it exists when the page loads).
You'll have to encode the values and comma-separate them (or similar), then parse the values out server-side.
Edit: Example
OK, I'd personally use jQuery for the JavaScript part, but I'll assume you're doing it 'raw'.
Say your markup (with a few added dynamic textboxes) looks like this:
<input type="hidden" id="hdnFormValues" />
<div id="dynamicForm">
<div id="textBoxArea">
<input type="text" id="newField1" /><br />
<input type="text" id="newField2" /><br />
<input type="text" id="newField3" /><br />
<input type="text" id="newField4" /><br />
</div>
<input type="submit" onclick="saveValues()" value="Save Values" />
</div>
and you have a JavaScript function that looks like this:
function saveValues()
{
theBoxes = document.getElementById('textBoxArea').getElementsByTagName('input');
hdnValues = document.getElementById('hdnFormValues');
hdnValues.value = "";
for(var i = 0; i < theBoxes.length; i++)
{
hdnValues.value += escape(theBoxes[i].value) + '|';
}
}
Then when the submit button gets pressed, the value of the HiddenField will become a pipe-delimited string of encoded values.
For example, if text boxes 1 through 4 had the values:
I'm
encoding
dynamic
values!
then the HiddenField's value would become I%27m|encoding|dynamic|values%21|
Remember, you'll need to output the function above from ASP.NET server side. Look at the ScriptManager documentation for how to do this. The reason is that the HiddenField's ID will be dynamic, so you can't (reliably) predict it before runtime.
Finally, in your server-side code that recieves the postback, you split out the delimited string and unencode it, then do what you want with the values.
The biggest caveat here is security and validation - although I've encoded the string, you need to do your own validation and security checks!

Categories