I'm trying to post data to the same page after postback with the help of ViewState. I fill out the contents of the page and post the form and display the input on the same page but the validator says that the firstname cannot be null while I just filled out the textbox before I submitted the form.
Default.aspx
<asp:Content ContentPlaceHolderID="Main" runat="server" EnableViewState="true">
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:Label ID="lbl1" Text="First Name" runat="server" />
</td>
<td>
<asp:TextBox ID="tFirstName" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ControlToValidate="tFirstName" ErrorMessage="This field cannot be empty."
runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lbl2" Text="Last Name" runat="server" />
</td>
<td>
<asp:TextBox ID="tLastName" runat="server" />
</td>
</tr>
</table>
</div>
<asp:Button ID="id" Text="Submit" runat="server" OnClick="Submit" />
<div>
<p>
<asp:Label ID="lTest" runat="server" /></p>
</div>
<asp:Label ID="lSubmit" runat="server" />
</form>
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
tFirstName.Text = (string)ViewState["tFirstName"];
tLastName.Text = (string)ViewState["tLastName"];
}
else
{
ViewState["tFirstName"] = tFirstName.Text;
ViewState["tLastName"] = tLastName.Text;
}
}
protected void Submit(object sender, System.EventArgs args)
{
try
{
lTest.Text = tFirstName.Text + " " tLastName.Text;
}
catch (Exception ex)
{
throw;
}
}
It seems my logic was wrong. The correct condition should be Page_Load() function:
if (!Page.IsPostBack)
{
tFirstName.Text = (string)ViewState["tFirstName"];
tLastName.Text = (string)ViewState["tLastName"];
}
It should be if (!Page.IsPostBack) instead of if (Page.IsPostBack)
:D
Have fun!
You are getting too confuse on this,
Below is the possible way to solve your issues. Before this, please learn about postback in page load
Seems you are passing the null values to the ViewState,
if (Page.IsPostBack)
{
tFirstName.Text = (string)ViewState["tFirstName"];
tLastName.Text = (string)ViewState["tLastName"];
}
else
{
ViewState["tFirstName"] = tFirstName.Text;
ViewState["tLastName"] = tLastName.Text;
}
Proceed as following
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostback==true)
{
if(ViewState["tFirstName"]!=null && ViewState["tLastName"]!=null)
{
tFirstName.Text = (string)ViewState["tFirstName"];
tLastName.Text = (string)ViewState["tLastName"];
}
}
}
protected void Submit(object sender, System.EventArgs args)
{
try
{
ViewState["tFirstName"] = tFirstName.Text;
ViewState["tLastName"] = tLastName.Text;
lTest.Text = tFirstName.Text + " " tLastName.Text;
}
catch (Exception ex)
{
throw;
}
}
I only want to point out, that you do NOT have to reassign values to the textboxes after a Postback. This is the normal asp.net web control behavior when EnableViewstate is turned on.
Remove your code from Page_Load and you should notice that textboxes remember values after a postback (unless you specifically remove it in behind code like tFirstName.Text = "")
Related
There are several posts on here with similar titles, but none that I have found actually exhibit the same behavior I'm seeing. I'm using buttons with MultiView as my navigation to give the appearance of tabs. The page loads, no problem. I can switch tabs, no problem. The issue I'm having occurs only when I press a different navigation button while a gridview is actively loading. If I wait for the gridview to fully load, I get no errors.
The full error I'm receiving is: Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
If I add the following, it does resolve my issue. However, I'm trying to avoid this if at all possible.
<%# Page ... EnableEventValidation = "false" />
default.aspx
<form id="form1" runat="server">
<table width="100%" align="center">
<tr style="background-color:#E9E9E9;">
<td>
<asp:Button Text="Tab1" BorderStyle="None" ID="Tab1Button" CssClass="Initial" runat="server"
OnClick="Tab1Button_Click" />
<asp:Button Text="Tab2" BorderStyle="None" ID="ConflictButton" CssClass="Initial" runat="server"
OnClick="ConflictButton_Click" />
<asp:Button Text="Tab3" BorderStyle="None" ID="Tab3Button" CssClass="Initial" runat="server"
OnClick="Tab3Button_Click" />
<asp:Button ID="AffiliateAddButton" runat="server" Text="Add" />
<asp:MultiView ID="MainView" runat="server">
<asp:View ID="View1" runat="server">
<table class="TabContent"><tr><td>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" DataSourceID="SqlDataSource1">
</asp:GridView>
</td></tr></table>
</asp:View>
<asp:View ID="View2" runat="server">
<table class="TabContent">
<tr>
<td>
View 2
</td>
</tr>
</table>
</asp:View>
<asp:View ID="View3" runat="server">
<table class="TabContent">
<tr>
<td>
View 3
</td>
</tr>
</table>
</asp:View>
</asp:MultiView>
</td>
</tr>
</table>
</form>
default.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Tab1Button.CssClass = "Clicked";
MainView.ActiveViewIndex = 0;
LoadGrid();
}
}
protected override void Render(HtmlTextWriter writer)
{
// Register controls for event validation
foreach (Control c in this.Controls)
{
this.Page.ClientScript.RegisterForEventValidation(
c.UniqueID.ToString()
);
}
base.Render(writer);
}
private void LoadGrid()
{
SqlDataSource1.CancelSelectOnNullParameter = false;
GridView1.DataSourceID = null;
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
private void ButtonsControl(string tab)
{
if(tab == "Tab1")
{
AffiliateAddButton.Visible = true;
Tab1Button.CssClass = "Clicked";
ConflictButton.CssClass = "Initial";
Tab3Button.CssClass = "Initial";
LoadGrid();
}
if (tab == "Tab2")
{
AffiliateAddButton.Visible = false;
Tab1Button.CssClass = "Initial";
ConflictButton.CssClass = "Clicked";
Tab3Button.CssClass = "Initial";
GridView1.DataSourceID = null;
GridView1.DataBind();
}
if (tab == "Tab3")
{
AffiliateAddButton.Visible = false;
Tab1Button.CssClass = "Initial";
ConflictButton.CssClass = "Initial";
Tab3Button.CssClass = "Clicked";
GridView1.DataSourceID = null;
GridView1.DataBind();
}
}
protected void Tab1Button_Click(object sender, EventArgs e)
{
ButtonsControl("Tab1");
MainView.ActiveViewIndex = 0;
}
protected void ConflictButton_Click(object sender, EventArgs e)
{
ButtonsControl("Tab2");
MainView.ActiveViewIndex = 1;
}
protected void Tab3Button_Click(object sender, EventArgs e)
{
ButtonsControl("Tab3");
MainView.ActiveViewIndex = 2;
}
What I ended up doing was two things:
Added paging. Ideally I didn't want this in this specific scenario but limiting my page to 500 lines made it load fast enough to almost eliminate this.
Switched from multiview to frameset. Again, not an ideal option, but works in my given scenario.
I am working on a project in which I am trying to have an empty label populate with the numbers that are being clicked. However, I am having trouble with my code behind my web form and cannot get it to work. My code behind:
public partial class WebForm : System.Web.UI.Page
{
ArrayList phoneNumber = new ArrayList() { };
int counter = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnNum1_Click(object sender, EventArgs e)
{
counter++;
phoneNumber[counter - 1] = 1;
lblNumbers.Text = phoneNumber.ToString();
}
protected void btnNum2_Click(object sender, EventArgs e)
{
counter++;
phoneNumber[counter - 1] = 1;
lblNumbers.Text = phoneNumber.ToString();
}
My web form:
<form id="form1" runat="server">
<div class="container">
<asp:Image class="img-fluid d-block mx-auto" ID="imgLogo" runat="server" ImageUrl="~/Images/logo.png"/>
<div style="text-align:center; font-size:x-large; font-weight:800">
<asp:Label ID="lblNumbers" runat="server" Text=""></asp:Label>
</div>
<table class="table table-bordered" style="margin:auto; width:250px; height:342px; background-image:url(Images/Telephone-keypad.png); background-repeat:no-repeat; background-position:center;" >
<tbody>
<tr>
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
<td><asp:Button ID="btnNum1" runat="server" OnClick="btnNum1_Click"/></td>
<td><asp:Button ID="btnNum2" runat="server" OnClick="btnNum2_Click"/></td>
<td><asp:Button ID="btnNum3" runat="server" OnClick="btnNum3_Click"/></td>
</tr>
<tr>
<td><asp:Button ID="btnNum4" runat="server" OnClick="btnNum4_Click"/></td>
<td><asp:Button ID="btnNum5" runat="server" OnClick="btnNum5_Click"/></td>
<td><asp:Button ID="btnNum6" runat="server" OnClick="btnNum6_Click"/></td>
</tr>
<tr>
<td><asp:Button ID="btnNum7" runat="server" OnClick="btnNum7_Click"/></td>
<td><asp:Button ID="btnNum8" runat="server" OnClick="btnNum8_Click"/></td>
<td><asp:Button ID="btnNum9" runat="server" OnClick="btnNum9_Click"/></td>
</tr>
<tr>
<td><asp:Button ID="btnStar" runat="server" OnClick="btnStar_Click"/></td>
<td><asp:Button ID="btnNum0" runat="server" OnClick="btnNum0_Click"/></td>
<td><asp:Button ID="btnPound" runat="server" OnClick="btnPound_Click"/></td>
</tr>
</tbody>
</table>
</div>
</form>
When each button is clicked, I want the numbers that are clicked to display in the label as they are clicked. Currently, when I click on a button, it gives me an error page that states:
Index was out of range. Must be non-negative and less than the size of the collection.
It also includes this:
Source Error:
Line 21: {
Line 22: counter++;
Line 23: phoneNumber[counter - 1] = 1;
Line 24: lblNumbers.Text = phoneNumber.ToString();
Line 25: }
Can someone please help?
Asp.net Pages are stateless, meaning your variables like "int counter" does not maintain its value between post backs. Because of this it will always be zero, you are then subtracting 1, which results in -1 which will result in the error that you are getting. Try saving the value in a session variable, or for even better results you could use javascript instead.
You need to append the value of the clicked number to the value in the label. Since you're in Webforms you can store it in ViewState instead of using a session variable (unless the user can come and go and your requirement is to preserve it).
I'd try something like this:
protected void btnNum1_Click(object sender, EventArgs e)
{
appendNumber(1);
}
.
.
.
private void appendNumber(int number)
{
counter++;
phoneNumber[counter - 1] = number;
ViewState["phoneNumber"] = phoneNumber.ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
if(!String.IsNullOrEmpty(ViewState["phoneNumber"].ToString()))
{
lblNumbers.Text = ViewState["phoneNumber"].ToString()
}
}
static int counter = 0;
use this ...and it will hold values between postbacks
No matter what combination I try, the button (ibtnDeleteDiaryEntry) simply will not raise an event although it does seem to do postback as it should. ViewState is turned on by default, read elsewhere that it is sometimes problematic. Also, I've used the Repeater's OnItemCommand property as required. Any kind of help is appreciated.
EDIT: It seems that the problem is somehow connected to the jQuery UI's Accordion Widget. The repeater is located within a div that is used to initialize the accordion. If I remove the div tags surrounding the repeater, the OnItemCommand event gets called. Very weird.
Markup:
<asp:Repeater ID="repAccordion" OnItemCommand="repAccordion_OnItemCommand" runat="server">
<ItemTemplate>
<h3> <%# "Date: " + Eval("date", "{0:d}") %>
<span class="deleteButtonContainer">
<asp:ImageButton ID="ibtnDeleteDiaryEntry" CommandArgument='<%# Eval("diary_entry_id") %>' CommandName="Delete" AlternateText="ibtnDeleteDiaryEntry" ImageUrl="images/remove_item.png" runat="server" />
</span>
</h3>
<div>
<table>
<tr>
<td>
<asp:Label ID="lblText" runat="server" ForeColor="#AA0114" Text="Text:"></asp:Label>
</td>
</tr>
<tr>
<td>
<%# Eval("text") %>
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
_db = new PersonalOrganizerDBEntities();
_diary_entryService = new Diary_EntryService();
_userService = new UserService();
if (!IsPostBack)
{
LoadItems();
}
}
public void LoadItems()
{
long currentUserId = (long) Session["userId"];
User currentUser = _userService.GetById(currentUserId);
Diary_Entry[] diaryEntriesArray =
_diary_entryService.GetAll().Where(current => current.diary_id == currentUser.user_id).ToArray();
if (diaryEntriesArray.Length == 0)
{
noItems.Text = "You currently have no diary entries.";
noItems.Visible = true;
}
else
{
noItems.Visible = false;
}
repAccordion.DataSource = diaryEntriesArray;
repAccordion.DataBind();
}
protected void repAccordion_OnItemCommand(object sender, RepeaterCommandEventArgs e)
{
Response.Write("test");
}
If it doesn't work I would recommend removing OnItemCommand from repeater and adding OnClick event for ImageButton instead. In OnClick event in code behind you can cast 'sender' to ImageButton and read CommandArgument value to get diary_entry_id.
Hi i am loading huge data by asp.net Ajax on button click in grid view showing loading message on update prgress ...in update progress time i have to disable my BtnLoadReport Button.
<td>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
<asp:UpdateProgress ID="updProgress"
AssociatedUpdatePanelID="UpdatePanel1"
runat="server" oninit="updProgress_Init" onprerender="updProgress_PreRender">
<ProgressTemplate>
<span style="color:green; font-style:italic;">Loading, please wait...</span>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<div id="DemoId">
<asp:Button ID="BtnLoadReport" runat="server" onclick="BtnLoadReport_Click"
Text="LoadReport" Width="176px" ClientIDMode="Static" OnClientClick="return clickOnLoadReport();" />
</div>
<asp:GridView ID="GridView1" runat="server" Height="170px"
onselectedindexchanged="GridView1_SelectedIndexChanged" Width="438px">
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="BtnLoadReport" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
my script to disable button
<script type="text/javascript">
var updateProgress = null;
function clickOnLoadReport() {
// This will disable all the children of the div
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm.get_isInAsyncPostBack()==false) {
var nodes = document.getElementById("DemoId").getElementsByTagName('*');
for (var i = 0; i < nodes.length; i++) {
nodes[i].disabled = true;
// nodes[i].off("click");
}
}
}
</script>
but it is not disabling my button for long it is disabling it for just seconds
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(this.BtnLoadReport);
}
protected void BtnLoadReport_Click(object sender, EventArgs e)
{
// System.Threading.Thread.Sleep(3000);
UpdatePanel1.Update();
DataSet dataSet = new DataSet();
dataSet.ReadXml(#"C\Data.Xml");
GridView1.DataSource = dataSet.Tables[0];
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void updProgress_Init(object sender, EventArgs e)
{
BtnLoadReport.Enable = false;
}
protected void updProgress_PreRender(object sender, EventArgs e)
{
BtnLoadReport.Enable
= true;
}
this above thing i tried to disable my button BtnLoadReport on Update progress still not working
Thanks in Advance
function clickOnLoadReport() {
var requestManager = Sys.WebForms.PageRequestManager.getInstance();
requestManager.add_initializeRequest(CancelPostbackForSubsequentSubmitClicks);
function CancelPostbackForSubsequentSubmitClicks(sender, args) {
if (requestManager.get_isInAsyncPostBack() &
args.get_postBackElement().id == 'BtnLoadReport') {
args.set_cancel(true);
document.getElementById("BtnLoadReport").setAttribute("disabled", "disabled");
//alert('A previous request is still in progress that was issued on clicking ' + args.get_postBackElement().id);
}
}
}
i made changes in my javascript function it solve my problem
I have a webs form page and I have a text box which once clicked passes a variable to the code behind and then back into another element of that page and I cannot get it to work.
This is the closest I have got.
<asp:Panel ID="Search" runat="server" Visible="true">
<tr>
<td>
<asp:Label ID="lblSearch" runat="server" Text="Search"></asp:Label>
</td>
<td>
<asp:TextBox ID="search" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="valSearch" runat="server"
ControlToValidate="movieSearch" Text="Please enter text" />
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Save"
OnClick="btnSubmit_Click" />
</td>
</tr>
</table>
</asp:Panel>
<asp:Panel ID="pnlSearchResult" runat="server" Visible="false">
<script>
var search = '<%=Server.UrlDecode(Request.QueryString["Data"]) %>';
</script>
</asp:Panel>
And the code behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValid)
{
pnlSearch.Visible = false;
pnlSearchResult.Visible = true;
Response.Redirect("search.aspx?Data=" + Server.UrlEncode(search.Text));
}
}
Also this does not change the visibility of the two panels for some reason.
I would appreciate any guidance I am very new to asp and c#.
The panel's visibility is not changing because you're forcing a new GET request to the page with this: -
Response.Redirect("search.aspx?Data=" + Server.UrlEncode(search.Text));
(I'm assuming your page is called 'search.aspx')
There's no need to do this. Remove this line.
Secondly, I see you want to force the textbox's Text value into a Javascript variable. Replace this
var search = '<%=Server.UrlDecode(Request.QueryString["Data"]) %>';
with this
var search = '<%= search.Text %>';
Write below code on page event.
Another more important point is you first panel Id is "Search" not "pnlSearch" on aspx page so please correct it
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Data"] != null)
{
Search.Visible = false;
pnlSearchResult.Visible = true;
}
}
I recommend solution without using Response.Redirect.
Code Behind Submit Button click:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValid)
{
pnlSearch.Visible = false;
pnlSearchResult.Visible = true;
}
}
In Markup:
<asp:Panel ID="pnlSearchResult" runat="server" Visible="false">
<script>
var searchTxt = document.getElementById('search');
if(searchTxt.value != null && searchTxt.value != ''){
//do your stuff
}
</script>