I have two buttons inside of the repeater and I'm trying to access them from code behind, but they are not working. I receive the following error:
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.
I don't understand what does the error mean nor where is coming from. Here is my code:
<asp:Repeater ID="Repeater1" runat="server"
onitemdatabound="Repeater1_ItemDataBound1"
onitemcommand="Repeater1_ItemCommand" >
<ItemTemplate>
<table>
<tr>
<td><asp:Image ID="Image1" runat="server" /></td>
<td><asp:Label ID="empnamelbl" runat="server" Text='<%# Eval("fullname") %>'></asp:Label></td>
<td><asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList></td>
<td> <asp:Button ID="Button1" runat="server" Text="Present" CommandName="test1" CommandArgument='<%# Eval("ID") %>' /> </td>
<td><asp:Button ID="Button2" runat="server" Text="Absent" CommandName="test2" CommandArgument='<%# Eval("ID") %>' /> </td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
Code behind:
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "test1")
{
Response.Write("hi");
}
}
I was able to solve it by using, UseSubmitBehavior="false", property in the buttons.
Here is it:
<asp:Button ID="Button2" UseSubmitBehavior="false" runat="server" Text="Absent" CommandName="test2" CommandArgument='<%# Eval("ID") %>' />
Try setting EnableViewState="false" for the repeater. Definitely there will be some drawbacks but this has worked for me.
Else below are some more approaches you can try on:
If you are setting your Repeater's DataSource in Page_Load event.
Try wrapping your Page_Load code inside if(!IsPostBack) .
protected void Page_Load( object sender , eventArgs e)
{
if(!IsPostBack)
{
// bind repeater , dropdownlist items ... here
}
}
Also from your error message it seems that enableEventValidation=“true” setting is present either in your Page as:
<%# Page EnableEventValidation="true" ... %>
OR in your web.config :
<system.web>
<pages enableEventValidation="true"/>
</system.web>
Some suggestions:
Disable eventvalidation. Easy to do but less secure .THIS IS NOT RECOMMENDED. Also read here an extremely good article on this issue: http://odetocode.com/blogs/scott/archive/2006/03/22/asp-net-event-validation-and-invalid-callback-or-postback-argument-again.aspx
If any client side method is used to set changes in Controls, It's better to use the
postback and add or remove the items server-side. Example: if a list control includes options numbered 1, 2, or 3 when the page is rendered, and if a postback request is received specifying option number 4, ASP.NET raises an exception.
This MSDN reference. is good too.
I hope this helps.
due to presence of Image that run at server .. try to use img tag instead
Related
I need to display popup when page loads. I have used ModelPopupExtender. It does shows on it's TargetControlID click but not showing on page load from code behind.
I have check many solutions on stack but none of them are working for me.
protected void Page_Load(object sender, System.EventArgs e)
{
this.mpOTP.Show();
}
<asp:Button ID="activateMpOtp" runat="server" Text="Open" ClientIDMode="Static"/>
<asp:ModalPopupExtender ID="mpOTP" runat="server" BackgroundCssClass="popup-overlay" PopupControlID="pnlOTP" CancelControlID="closeOTP" TargetControlID="activateMpOtp"></asp:ModalPopupExtender>
<asp:Panel ID="pnlOTP" runat="server" CssClass="popup-dialogue">
</asp:Panel>
Getting this error in console
Your markup is not correct.
First of all, you need to register AjaxControlToolKit controls by using the following directive at the top of your page markup, just after the page directive.
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="act %>
Then, your markup should look like the following. Problems with your markup are listed below.
You have not included markup for the cancel button
and also your control prefix is wrong since it should not be asp which is the prefix is for ASP.Net Microsoft controls and not for AJAXControlToolKit (NOTE: you give this prefix in your register directive for AjaxControl,Toolkit, which is act in code sample given, but you could give any prefix and use it for modalpopuextender)
Correct markup for ModalPopupExtender
<asp:Button ID="activateMpOtp" runat="server" Text="Open" ClientIDMode="Static"/>
<act:ModalPopupExtender ID="mpOTP" runat="server" BackgroundCssClass="popup-overlay"
PopupControlID="pnlOTP" CancelControlID="closeOTP"
TargetControlID="activateMpOtp"></act:ModalPopupExtender>
<asp:Panel ID="pnlOTP" runat="server" CssClass="popup-dialogue">
<div class="header">
Modal Popup
</div>
<div class="body">
Your content goes here
<br />
<asp:Button ID="closeOTP" runat="server" Text="Close" />
</div>
</asp:Panel>
I've been banging my head against the wall for the last couple of days trying to get this scenario to work.
I have an <asp:UpdatePanel> on a page which has an external trigger and contains a Telerik RadListView:
<asp:UpdatePanel runat="server" ID="RationUpdatePanel" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<telerik:RadListView ID="RationListView runat="server"
DataSourceId="RationDataSource"
OnItemCanceling="ItemCancelingHandler"
OnItemEditing="ItemEditingHandler"
OnItemUpdating="ItemUpdateHandler">
<LayoutTemplate>
<table>
<thead>
<tr>...</tr>
</thead>
<tbody>
<tr id="itemPlaceHolder" runat="server"/>
</tbody>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" ToolTip="Edit" />
<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" ToolTip="Delete" />
</td>
<td>...</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr>
<td>
<asp:LinkButton ID="SaveButton" runat="server" CausesValidation="False" CommandName="Save" Text="Save" ToolTip="Save" />
<asp:LinkButton ID="CancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" ToolTip="Update" />
</td>
<td>...</td>
</tr>
</EditItemTemplate>
</telerik:RadListView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UseRationButton" EventName="Click" />
</Triggers>
</UpdatePanel>
Code behind looks like this:
protected void RationListView_ItemEditing(object sender, RadListViewCommandEventArgs e)
{
((RadListViewDataItem)e.ListViewItem).Edit = true;
}
protected void RationListView_ItemCanceling(object sender, RadListViewCommandEventArgs e)
{
RationListView.ClearEditItems();
((RadListViewDataItem)e.ListViewItem).Edit = false;
}
Clicking on the EditButton or CancelButton produced the expected events and the ObjectDataSource routine to rebind the list is called, yet the update panel is not refreshed. Calling RationUpdatePanel.Update() from the event handlers does not change the situation. The code works properly outside of an update panel: the mode changes and the buttons from the other template are displayed.
In either scenario clicking on the external trigger causes the list to be displayed.
Update: I added a couple of javascript callbacks to the PageManager class in the browser for beginRequest and endRequest. These just display an alert when the event occurs.
The page contains several elements which basically look like this (details omitted):
<div>
<div>
<asp:DropDownList ID="RationDdl"/>
<asp:Button ID="UseRationButton"/>
</div>
<div>
<asp:DropDownList ID="AnimalGroupDdl"/>
<asp:UpdatePanel ID="AnimalWeightUpdatePanel"/>
<ContentTemplate>
<asp:DropDownList ID="AnimalWeightDdl"/>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
<div>
<telerik:RadListBox>
</telerik:RadListBox>
</div>
<div>
<asp:UpdatePanel ID="FeedPreviewUpdatePanel">
<ContentTemplate>
<asp:Repeater>
</asp:Repeater>
</ContentPanel>
</asp:UpdatePanel>
</div>
<div>
<!-- this contains the update panel shown above -->
</div>
The UseFeedRationButton in the first div is an external trigger for the RationUpdatePanel. AnimalGroupDdl is an external trigger for AnimalWeightUpdatePanel. The handler for the SelectedIndexChanged event on AnimalGroupDdl populates AnimalWeightDdl with available weight classes for the
selected group. It has no interaction with RationUpdatePanel or FeedPreviewUpdatePanel.
Here is the markup for UseRationButton:
<asp:Button ID="UseRationButton" runat="server"
Text="Use This Ration"
OnClick="UseRationButton_Click"
CausesValidation="true"
ValidationGroup="UseRation"
UseSubmitBehavior="false">
</asp:Button>
And here is the code behind:
protected void UseRationButton_Click(object sender, EventArgs e)
{
string text = this.RationDdl.SelectedItem.Text;
this.RationNameLabel.Text = text;
this.RationDataSource.SelectParameters["RationId"].DefaultValue = this.RationDdl.SelectedValue;
}
There are two scenarios I have been testing:
1) Choose a ration from RationDdl and click UseRationButton
2) Choose an animal group and then execute scenario 1.
In scenario 1 an async postback is initiated by the client side asp.net code and the button event is handled server side. The RationListView is populated but the client side endRequest code is never executed (the alert is not displayed). Subsequent clicks on the controls in the RadListView trigger an async postback but the state of the list is not changed and the client side endRequest code is not executed.
In scenario 2 an async postback is initiated, the event is handled on the server side and AnimalWeightDdl is populated. The client side endRequest code is executed in this case (the alert IS displayed). Subsequent to this selecting a ration and clicking on the use ration button initiates a postback, the list view is populated and the endRequest code is executed. At his point clicking on buttons in the list view causes an async postback to be initiated, the state of the list is changed and the endRequest code is executed.
My working theory is that something is causing the state of the page request manager class on the client to become fubared, but I can't figure out what might be causing it.
Firstly , If you use telerik rad control , I suggest you to change your asp:button to telerik:RadButton .
Here is example
<telerik:RadButton ID="v" runat="server" Text="Use This Ration"
AutoPostBack="true"
ValidationGroup="UseRation" OnClick="UseRationButton_Click">
</telerik:RadButton>
protected void UseRationButton_Click(object sender, EventArgs e)
{
string text = this.RationDdl.SelectedItem.Text;
this.RationNameLabel.Text = text;
this.RationDataSource.SelectParameters["RationId"].DefaultValue = this.RationDdl.SelectedValue;
}
Note that , you should add AutoPostBack="true" into your radButton .
And this links , MSDN Reference1 and MSDN Reference2 will show details of using update Panel .
The research I did late Friday and Saturday morning provided the answer to this one.
I had some code attached to the Sys.WebForms.PageRequestManager endRequest event which updated a text box which contained a temporary title for a new ration. The code looked like this:
///
/// reregister the change handlers after reloading the animal weight ddl and create a
/// temporary name for the ration based on animal choice and weight.
///
function animalWeightDdlOnLoad() {
var ddl = document.getElementById("<%= AnimalWeightDdl.ClientID %>");
//
// add event handler in a browser agnostic fashion
//
if (ddl.addEventListener) {
ddl.addEventListener("change", animalWeightDdlOnChange);
}
else if (ddl.attachEvent) {
ddl.attachEvent("onchange", animalWeightDdlOnChange);
}
else {
ddl.onchange = animalWeightDdlOnChange;
}
animalWeightDdlOnChange();
}
animalWeightDdlOnChange() referenced the options list of the animal weight ddl:
///
/// create a temporary name for the ration
///
function animalWeightDdlOnChange() {
var ddl1 = document.getElementById("<%= AnimalGroupDdl.ClientID %>");
var ddl2 = document.getElementById("<%= AnimalWeightDdl.ClientID %>");
var text = document.getElementById("<%= RationNameText.ClientID %>");
text.value = ddl1.options[ddl1.selectedIndex].text + ' ' + ddl2.options[ddl2.selectedIndex].text + ' - Copy';
}
However if the list had not yet been populated the reference to options caused a fault which halted endRequest processing. Rather than having this code run on every async request I changed it to be a handler for the change event on the animal group ddl, like this:
function animalGroupDdlOnSelectedChanged() {
//
// add a handler for the endRequest event which will be triggered by
// fetching the contents of the weight ddl.
//
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(animalWeightDdlOnLoad);
}
Then in animalWeightDdlOnLoad() I added a line to remove the handler once the request had
run. This ensured that the change handler for the weight ddl would only run once the list had been populated. Problem solved. But just in case, I added a check on the length of the animal weight ddl's options list.
So even seemingly innocent javascript can mess up your async request handling in the browser.
I have a search form in an updatePanel which retrieves a list of users in a grid in the same UpdatePanel. The name of each user is a commandLink. I want to make the commandLinks as PostBackTriggers.
But when I do it I get an error at the pageLoad time that the controlId does not exist and its true because the grid of users does not render at the load time but through an ajax call.
Any ideas on how can I make the multiple command buttons in a grid retrieved through ajax call as post back triggers?
When adding the items to the grid, within the ItemDataBound event handler, you should register the postback for each specific control (the static identifiers in your HTML declarations are essentially placeholders - not all things repeated in the grid can actually have the same ID). You do this using the ScriptManager.RegisterAsyncPostBackControl method:
The RegisterAsyncPostBackControl method enables you to register Web
server controls as triggers so that they perform an asynchronous
postback instead of a synchronous postback. When the
ChildrenAsTriggers property of an UpdatePanel control is set to true
(which is the default), postback controls inside the UpdatePanel
control are automatically registered as asynchronous postback
controls.
As stated above, using ChildrenAsTriggers is a possibility, too, but this is commonly set to false for more stringent management.
I have found the solution. Here is the code on asp
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" Text="Search" />
<asp:GridView ID="gvSearchResult" runat="server" OnRowCommand="gvSearchResult_RowCommand"
OnRowDataBound="gvSearchResult_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnDetail" runat="server" CommandArgument='<%# Bind("CNIC") %>' CommandName="Detail">
<asp:Label ID="lblName" Text='<%# Bind("Employee_Name") %>' runat="server</asp:Label>
</asp:LinkButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle"Height="25px"Width="30%" />
</asp:TemplateField>
</Columns>
</asp:GridView>
Ihad to place OnRowDataBound="gvSearchResult_RowDataBound" on gridView and that function looks like below. So I had to register the iterative control in Scriptmanager as PostBackControl in RowDataBound event of GridView.
protected void gvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
LinkButton lnkbtnDetail = (LinkButton)e.Row.FindControl("lnkbtnDetail");
ScriptManager.GetCurrent(this).RegisterPostBackControl(lnkbtnDetail);
}
}
catch (Exception ex)
{
}
}
I am having problem with my repeater's OnItemCommand event.
When I click the Link Button, its not firing.
Am I missing any environment variable
ASPX code
<table>
<!-- repResearchers begin, 0=display name, 1=url -->
<asp:Repeater ID="repExtResearchers" Runat="server" OnItemCommand="deleteResearcher">
<ItemTemplate>
<tr>
<td>
<a href="<%# ((System.String[])Container.DataItem)[1] %>">
<%# ((System.String[])Container.DataItem)[0] %></a>
</td>
<td>
<asp:LinkButton ID="lbDelete" runat="server" CommandName="del"
CommandArgument = "<%# ((System.String[])Container.DataItem)[1]%>"
OnClientClick="if (!confirm('Are you sure do you want to delelte it?')) return false;">Delete</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
CS
protected void deleteResearcher(object sender, RepeaterCommandEventArgs e)
{
string a;
lblError.Text = e.CommandArgument.ToString();
lblError.Visible = true;
}
Make sure you dont rebind the repeater at every postback.
If (Page.IsPostBack)
return;
repExtResearchers.DataSource = ...
repExtResearchers.DataBind();
Hope that helps.
I'm sure - as this is an EXTREMELY old question - that this has been answered already, but for people who may be running into what I was running into...
If you're using any of the Ajax Controls, they all require a validation group. I had a really long page that I was trying to shorten by doing this, so I wasn't noticing that the ajax controls from the Ajax Control Toolkit were throwing errors and not validating. I set the LinkButton's validation group to something that was nowhere anywhere and it started firing.
Hopefully, that helps someone out.
It won't fix your ptoblem but change
OnClientClick="if (!confirm('Are you sure do you want to delelte it?')) return false;"
to
OnClientClick="return confirm('Are you sure do you want to delelte it?')"
Your code is using a double negative to confirm a positive.
I had this issue using OnCommand in a LinkButton and I had an empty href="". When I removed the extra attribute, it posted back.
This is a weird issue. I have a List view with 2 Link buttons. "Edit" and "Delete"
Iam able to attach an event handler for the first linkbutton(Update). Code in the event handler executed fine. But If I try to attach a event handler for the second link button(Delete) , I get an error.
My Item Template Looks like this.
<ItemTemplate>
<tr>
<td>
<asp:Label ID="MessageLabel" runat="server" Text='<%# Eval("Item") %>' />
</td>
<td>
<asp:Label ID="URLLabel" runat="server" Text='<%# Eval("URL") %>' />
</td>
<td>
<asp:LinkButton ID="EditLinkButton" runat="server" OnClick="EditLinkButtonClicked"
CommandArgument='<%# Eval("ItemID") %>'> Edit</asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="DeleteLinkButton" runat="server" OnClick="DeleteLinkButtonClicked"
CommandArgument='<%# Eval("ItemID") %>'>Delete</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
The Event handler declared in the codebehind file are
public void EditLinkButtonClicked(object sender, EventArgs e)
{
-----
}
public void DeleteLinkButtonClicked(object sender, EventArgs e)
{
-----
}
[Exactly same]
First Item works absolutely fine. But If I attach the second handler, I get the following error
Am I missing some thing ?
Note - There is no error if I try to attach the 1st event handler to the second link button.[ie EditLinkButtonClicked to DeleteLinkButtonClicked ]
Issue occurs only when I try to attach DeleteLinkButtonClicked to DeleteLinkButton
Any help? Thanks in Advance
Try to disable EnableEventValidation for the Page directive and check it.
<%# Page EnableEventValidation="false" %>
If it help then you should to know that:
This feature reduces the risk of
unauthorized or malicious postback
requests and callbacks. It is strongly
recommended that you do not disable
event validation.
regarding to http://msdn.microsoft.com/en-us/library/system.web.ui.page.enableeventvalidation.aspx
and try to avoid this in the way that was suggested here.
It'd be three things:
You need to clean, rebuild solution, and reset IIS or close ASP.NET development server (maybe some cache is preventing you to execute the most recent version of the code-behind class).
Typo. Double-check that...!
Event handler hasn't the right signature.
Anyway, why don't you use the "Command" event?
You can do OnCommand="Item_Command" and the event handler will have CommandEventArgs which provides you the CommandName and CommandArgument, so you can switch the command name and invoke the logic for editing or deleting respectively.
Read more here:
http://msdn.microsoft.com/es-es/library/system.web.ui.webcontrols.commandeventargs_members.aspx
The same problem occurs in my code. I resolved by using CausesValidation="false"
<asp:LinkButton ID="YourID" runat="server" **CausesValidation="false"** OnClick="Category_btn_Click1" />