HttpRequestValidationException on PostBack within UpdatePanel - c#

HttpRequestValidationException occurs when I try post when txtBulletin contains any HTML, like "Hello<br />World"
Bulletin.aspx
<asp:UpdatePanel ID="upContent" runat="server" UpdateMode="Always">
<ContentTemplate>
<div class="content bulletin-content">
<asp:TextBox ID="txtBulletin" runat="server"
TextMode="MultiLine" />
<div class="bulletin-edit">
<asp:ImageButton ID="btnSaveBulletin" runat="server"
ImageUrl="~/images/icons/check.gif"
CommandName="SaveChanges"
OnCommand="btnEditBulletin_Click"
Visible="false" />
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
Bulletin.aspx.cs
protected void btnEditBulletin_Click(object sender, CommandEventArgs e)
{
if (e.CommandName == "Edit")
{
// Do something
}
else if (e.CommandName == "SaveChanges")
{
// Do something
}
else if (e.CommandName == "Cancel")
{
// Do something
}
}
I have no idea how to bypass this, or why it evens does the validation for me. On error, the page no longer handles any PostBack events until I refresh the page.

ASP.NET checks POST values for potentially dangerous strings. This is done to prevent DoS attacks and the like.
To disable this, you'll need to edit the web.config file. Make sure the following element exists under <system.web>:
<pages validateRequest="false" />
Alternatively, to turn off request validation on a page-by-page basis, set the ValidateRequest property to false in the #Page declaration at the top of the ASPX page in question.
EDIT: Included details about how to turn request validation off for specific pages.

Related

UpdatePanel triggers not firing

I have problem with UpdatePanel (ASP.Net WebForms, .Net 4.0). Here is code:
<div class="container-fluid">
<form id="form1" runat="server">
<h2>Poruke</h2>
<div class="row">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<asp:UpdatePanel ID="msgListUpdatePanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="False">
<ContentTemplate>
<div class="col-md-4">
<asp:ListBox ID="msgList" runat="server" OnSelectedIndexChanged="msgList_SelectedIndexChanged" AutoPostBack="true" ClientIDMode="AutoID"></asp:ListBox>
</div>
<div class="col-md-8">
<asp:ListBox ID="conversationList" runat="server" ClientIDMode="AutoID"></asp:ListBox>
<br class="divider" />
<p>
Odgovor: <span>
<asp:TextBox ID="replyTxtbox" runat="server"></asp:TextBox></span>
</p>
<asp:Button ID="sendBtn" runat="server" Text="PoĊĦalji" OnClick="sendBtn_Click" EnableViewState="false" ClientIDMode="AutoID" />
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="msgList" EventName="SelectedIndexChanged"/>
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</div>
and this is codebehind...
int userIdCookie = 0;
message selected = new message();
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.User.Identity.IsAuthenticated)
{
FormsAuthentication.RedirectToLoginPage();
}
if (!Page.IsPostBack)
{
if (Int32.TryParse(HttpContext.Current.User.Identity.Name, out userIdCookie))
{
message msg = new message();
var allMsg = msg.allMessagesFormatted().Distinct().ToList();
msgList.DataSource = allMsg;
msgList.DataBind();
}
}
else
{
// test only!
replyTxtbox.Text = msgList.SelectedIndex.ToString();
msgListUpdatePanel.Update();
}
}
protected void msgList_SelectedIndexChanged(object sender, EventArgs e)
{
message msg = new message();
var allMsg = msg.allMessagesFormatted().Distinct().ToList();
msgList.DataSource = allMsg;
IList<message> boundList = (IList<message>)msgList.DataSource;
selected = boundList[msgList.SelectedIndex];
var conversation = msg.allMessagesFormatted().FindAll(x => x.conversationGuid == selected.conversationGuid);
conversationList.DataSource = conversation;
conversationList.DataBind();
}
protected void sendBtn_Click(object sender, EventArgs e)
{
if(selected.recipientId != 0)
{
message newmsg = new message();
newmsg.senderId = userIdCookie;
newmsg.recipientId = selected.recipientId;
newmsg.subject = selected.subject;
newmsg.messageTxt = replyTxtbox.Text;
newmsg.conversationGuid = selected.conversationGuid;
newmsg.time = DateTime.Now;
newmsg.Add();
}
}
msgList gets populated fine but when i change selection, nothing happens - its SelectedIndex event never fires. If I set AutoPostBack="true" to this listbox, it reloads page (which is exactly what I am trying to avoid).
To sum up - when i click on item in ListBox inside UpdatePanel, nothing happens (event isn't fired). I want to avoid page reload when selected index changes. I've tried dozen of solutions (ClientID, AsyncPostBack, "regular" PostBack triggers and I guess i missed one simple detail and it's driving me mad.
Can anyone help?
edit - as #mason pointed out, problem was in overidden message.ToString() method that contained \r\n chars which caused problems in postback.
You will receive a JavaScript error in your browser's console.
Uncaught Sys.WebForms.PageRequestManagerServerErrorException:
Sys.WebForms.PageRequestManagerServerErrorException: 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.
MsAjaxJs?v=c42ygB2U07n37m_Sfa8ZbLGVu4Rr2gsBo7MvUEnJeZ81:1 Uncaught
Sys.WebForms.PageRequestManagerServerErrorException:
Sys.WebForms.PageRequestManagerServerErrorException: 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.
You can see a simpler version if you use:
msgList.DataSource = new List<string>(){"A\r\n","B\r\n","C\r\n"};
When you watch it in the browser tab, you'll see POST request sent to the server, but on the server side the Page_Load method won't get hit at all.
The fix is either to not use \r\n characters in the data being used for the ListBox or to follow the directions to register it at ClientScriptManager.RegisterForEventValidation on MSDN.

How to hide and display asp:buttons in asp.net from code behind?

I am working on asp.net web application.
In one Page I have two asp buttons.
I want to display them in one condition otherwise I don't want to display them.
So I'm trying to do the same like this. But Its not working.
I can't find the reason behind it. Please tell me where is the issue.
To Hide Buttons
if (!IsPostBack)
{
ButtonReplaceId.Style.Add("display", "none");
ButtonAssociateRules.Style.Add("display", "none");
}
To display buttons
protected void ApplyAssociation(object sender, EventArgs e)
{
//Some piece of code
if(a==0)
{
ButtonAssociateRules.Style.Add("display", "block");
ButtonReplaceId.Style.Add("display", "block");
}
}
aspx for buttons
<div style ="padding-left:400px;">
<asp:Button ID="ButtonAssociateRules" runat="server" OnClick="AssociateMultipleRulesButtonClick"
CssClass="search_button_in_vm_intersection" Text="Associate Multiple Rules"
OnClientClick="return OnClientClickAssociateRewardRuleFile();" />
<asp:Button ID="ButtonReplaceId" runat="server" OnClick="ApplyReplaceIfRuleIntersects"
CssClass="search_button_in_vm_intersection" Text="Replace Previous Rules"
OnClientClick="return OnClientClickReplaceRewardRuleFile();" />
</div>
aspx of button for OnClick event ApplyAssociation()
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Table runat="server" CssClass="rule_file_whole" BorderWidth="0" Style="padding-top: 30px;">
<asp:TableRow ID="MerchantRowAssociation" HorizontalAlign="Center">
<asp:TableCell>
<div style="text-align: center">
<asp:Button ID="AssociationMerchant" Text="Apply Association" runat="server" OnClick="ApplyAssociation"
CssClass="search_button_in_vm_associate1 " OnClientClick="return checkValidation()" />
</div>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</ContentTemplate>
</asp:UpdatePanel>
Seeing as you are using a conditional update panel, you can try either of these after putting the buttons inside an update panel.
protected void ApplyAssociation(object sender, EventArgs e)
{
//Some piece of code
if (a == 0)
{
ButtonAssociateRules.Style["visibility"] = "hidden";
ButtonReplaceId.Style["visibility"] = "hidden";
myUpdatePanel.Update();
}
}
protected void ApplyAssociation(object sender, EventArgs e)
{
//Some piece of code
if (a == 0)
{
ButtonAssociateRules.Visible = false;
ButtonReplaceId.Visible = false;
myUpdatePanel.Update();
}
}
Here's an example of your buttons inside an update panel.
<asp:UpdatePanel ID="myUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div style="padding-left:400px;">
<asp:Button ID="ButtonAssociateRules" runat="server" OnClick="AssociateMultipleRulesButtonClick"
CssClass="search_button_in_vm_intersection" Text="Associate Multiple Rules"
OnClientClick="return OnClientClickAssociateRewardRuleFile();" />
<asp:Button ID="ButtonReplaceId" runat="server" OnClick="ApplyReplaceIfRuleIntersects"
CssClass="search_button_in_vm_intersection" Text="Replace Previous Rules"
OnClientClick="return OnClientClickReplaceRewardRuleFile();" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
You can simple use the Visible property of Button which is more straight forward and clean.
ButtonReplaceId.Visible = false;
If this property is false, the server control is not rendered. You
should take this into account when organizing the layout of your page.
If a container control is not rendered, any controls that it contains
will not be rendered even if you set the Visible property of an
individual control to true. In that case, the individual control
returns false for the Visible property even if you have explicitly set
it to true. (That is, if the Visible property of the parent control is
set to false, the child control inherits that setting and the setting
takes precedence over any local setting.) MSDN.
You are trying to change the state of control in ajax call that is not in current UpdatePanel. Put the buttons in the same UpdatePanel then you will be able to change the state.
ButtonReplaceId.Visible = false;
ButtonAssociateRules.Visible = false;

ValidationSummary in MasterPage hide success label

I've got a ValidationSummary and SuccessLabel in the MasterPage
When the SuccessLabel has detail in it, and then the ValidationSummary then fails validation I want it to hide the SuccessLabel and only show the ValidationSummary.
<div id="ApplicationStatus" class="ValidationSummaryContainer">
<asp:Label ID="StatusLabel" CssClass="SuccessSummary" runat="server"
Visible="false"></asp:Label>
<asp:Label ID="WarningLabel" CssClass="WarningSummary" runat="server"
Visible="false"></asp:Label>
<asp:ValidationSummary ID="ErrorValidationSummary" runat="server"
CssClass="ValidationSummary" DisplayMode="List" />
<asp:CustomValidator ID="ErrorCustomValidator" runat="server"></asp:CustomValidator>
</div>
<div id="ApplicationContent" class="ApplicationContentContainer">
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</div>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
StatusLabel.Text = "Successfully loaded record";
}
}
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<asp:Textbox ID = "Text1" runat="server"/>
<asp:RequiredFieldValidator id="InputTextBoxRequiredFieldValidator" runat="server"
ControlToValidate="Text1" Visible="false" CssClass="InlineNoWrap" Enabled="true">
</asp:RequiredFieldValidator>
<asp:Button ID = "Button1" runat="server" Text="Submit"/>
</asp:Content>
I'm trying to find a way in JavaScript to catch the validation error and hide the StatusLabel.
I don't want to have to put a javascript function on every button on every page that uses the MasterPage.
Thanks,
Alex
How about something like this:
protected void Submit(object sender, EventArgs e)
{
if (IsValid)
{
StatusLabel.Visible = true;
}
else
{
StatusLabel.Visible = false;
}
}
Your validation code are totally miss lot of fields.
ok now we are going your pint .
Set visible false in your label for page load event
then success time add the label text ,and set visible true
you miss control to validate and validationgroup and display fields
please see this sample

ASP.NET Repeater: Button in item template to redirect to another page

I have a repeater and each item contains a button which should redirect to another page and also pass a value in the query string.
I am not getting any errors, but when I click the button, the page just refreshes (so I am assuming a postback does occur) and does not redirect. I think that for some reason, it isn't recognizing the CommandName of the button.
Repeater code:
<asp:Repeater ID="MySponsoredChildrenList" runat="server" OnItemDataBound="MySponsoredChildrenList_ItemDataBound" OnItemCommand="MySponsoredChildrenList_ItemCommand">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<br />
<div id="OuterDiv">
<div id="InnerLeft">
<asp:Image ID="ProfilePic" runat="server" ImageUrl='<%#"~/Resources/Children Images/" + String.Format("{0}", Eval("Primary_Image")) %>'
Width='300px' Style="max-height: 500px" /></div>
<div id="InnerRight">
<asp:HiddenField ID="ChildID" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "Child_ID") %>'/>
<span style="font-size: 20px; font-weight:bold;"><%# DataBinder.Eval(Container.DataItem, "Name") %>
<%# DataBinder.Eval(Container.DataItem, "Surname") %></span>
<br /><br /><br />
What have you been up to?
<br /><br />
<span style="font-style:italic">"<%# DataBinder.Eval(Container.DataItem, "MostRecentUpdate")%>"</span>
<span style="font-weight:bold"> -<%# DataBinder.Eval(Container.DataItem, "Update_Date", "{0:dd/MM/yyyy}")%></span><br /><br /><br />Sponsored till:
<%# DataBinder.Eval(Container.DataItem, "End_Date", "{0:dd/MM/yyyy}")%>
<br /><br />
<asp:Button ID="ChildProfileButton" runat="server" Text="View Profile" CommandName="ViewProfile" />
</div>
</div>
<br />
</ItemTemplate>
<SeparatorTemplate>
<div id="SeparatorDiv">
</div>
</SeparatorTemplate>
</asp:Repeater>
C# Code behind:
protected void MySponsoredChildrenList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
// Stuff to databind
Button myButton = (Button)e.Item.FindControl("ChildProfileButton");
myButton.CommandName = "ViewProfile"; }
}
protected void MySponsoredChildrenList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "ViewProfile")
{
int ChildIDQuery = Convert.ToInt32(e.Item.FindControl("ChildID"));
Response.Redirect("~/ChildDescription.aspx?ID=" + ChildIDQuery);
}
}
I am new to using repeaters so it's probably just a rookie mistake. On a side note: is there a better way of obtaining the ChildID without using a hidden field?
EDIT: Using breakpoints; the ItemDatabound event handler is being hit, but the ItemCommand is not being entered at all
You need to set MySponsoredChildrenList_ItemDataBound as protected. Right now, you have just 'void' which by default is private, and is not accessible to the front aspx page.
Another way is to use the add event handler syntax from a function in your code behind, using the += operator.
Either way, the breakpoint will now be hit and our code should mwork.
EDIT: So the above solved the compilation error but the breakpoints are not being hit; I've ran some tests and am able to hit breakpoints like this:
Since I do not know how you are databinding, I just added this code to my code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MySponsoredChildrenList.DataSource = new List<object>() { null };
MySponsoredChildrenList.DataBind();
}
}
Note: If you DataBind() and ItemDataBound() is called on every postback, it will wipe out the command argument, which is potentially what you are seeeing; so if you always see [object]_ItemDataBound() breakpoint hit, but never [object]_ItemCommand(), it is because you need to databind only on the initial page load, or after any major changes are made.
Note also the method MySponsoredChildrenList_ItemCommand doesn't work:
protected void MySponsoredChildrenList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "ViewProfile")
{
int ChildIDQuery = Convert.ToInt32(e.Item.FindControl("ChildID"));
Response.Redirect("~/ChildDescription.aspx?ID=" + ChildIDQuery);
}
}
When you do FindControl, you need to cast to the correct control type, and also make sure to check for empty and null values before converting, or else you will possibly have errors:
protected void MySponsoredChildrenList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "ViewProfile")
{
int childId = 0;
var hiddenField = e.Item.FindControl("ChildID") as HiddenField;
if (null != hiddenField)
{
if (!string.IsNullOrEmpty(hiddenField.Value))
{
childId = Convert.ToInt32(hiddenField.Value);
}
}
if (childId > 0)
{
Response.Redirect("~/ChildDescription.aspx?ID=" + childId);
}
}
}
Hope this helps - if not, please post additional code for the "full picture" of what is happening, so we can see where else you might have a problem.
I think on the repeater you need to add
OnItemDataBound="MySponsoredChildrenList_ItemDataBound"
Not 100% sure, but could be the same for the ItemCommand.
--
In regards to obtaining the ChildID. Add a CommandArgument to the button in the repeater, and set it in the same way, <% Eval("ChildID") %>. This can the be obtained using e.CommandArgument.
Try this.. Add an attribute to item row
row.Attributes["onclick"] = string.Format("window.location = '{0}';", ResolveClientUrl(string.Format("~/YourPage.aspx?userId={0}", e.Item.DataItem)) );
or You can do like this also
<ItemTemplate> <tr onmouseover="window.document.title = '<%# Eval("userId", "Click to navigate onto user {0} details page.") %>'" onclick='window.location = "<%# ResolveClientUrl( "~/YourPage.aspx?userId=" + Eval("userid") ) %>"'> <td> <%# Eval("UserId") %> </td> </tr> </ItemTemplate>

ASP.NET HoverMenuExtender Lazy Loading

I'm trying to get my hovermenuextenders to do some lazy loading. I have avatars across the site that when hovered over should pull back various things (images, recent posts, post count, etc) For obvious reasons I don't want to do this for all avatars on the page_load.
Using the following code I'm able to get the hover event to trigger a postback to the server asynchronously (breakpoint is hit onmouseover). However, the commands in the postback don't seem to be reflected after execution is done. The loading image/label stay in the hover panel. Any help is appreciated!
EDIT: I just realized that the very last avatar rendered on the page works properly but none of the ones above it do. Any ideas what might be causing this strange behavior?
<script language="javascript" type="text/javascript">
function OnHover(image) {
__doPostBack('<%= this.imageHoverTrigger.UniqueID %>', '');
}
</script>
<!-- DUMMY Hover Trigger -->
<input id="imageHoverTrigger" runat="server" style="display:none;"
type="button" onserverclick="imageHoverTrigger_Click" />
<!-- User Avatar -->
<div style="border: solid 1px #AAA; padding:2px; background-color:#fff;">
<asp:ImageButton ID="UserImg" runat="server" />
</div>
<!-- Hover tooltip disabled by default
(Explicitly enabled if needed)-->
<ajax:HoverMenuExtender ID="UserInfoHoverMenu" Enabled="false" runat="server"
OffsetX="-1"
OffsetY="3"
TargetControlID="UserImg"
PopupControlID="UserInfoPanel" dyn
HoverCssClass="userInfoHover"
PopupPosition="Bottom">
</ajax:HoverMenuExtender>
<!-- User Profile Info -->
<asp:Panel ID="UserInfoHover" runat="server" CssClass="userInfoPopupMenu">
<asp:UpdatePanel ID="UserInfoUpdatePanel" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:Image ID="loadingImg" runat="server" ImageUrl="~/Design/images/ajax-loader-transp.gif" />
<asp:Label ID="loadingLbl" runat="server" Text="LOADING..." ></asp:Label>
<asp:Panel ID="UserInfo" runat="server" Visible="false">
<b><asp:Label ID="UserNameLbl" runat="server"></asp:Label><br /></b>
<span style="font-size:.8em">
<asp:Label ID="UserCityLbl" runat="server" Visible="false"></asp:Label> <asp:Label ID="UserStateLbl" runat="server" Visible="false"></asp:Label>
</span>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="imageHoverTrigger" />
</Triggers>
</asp:UpdatePanel>
</asp:Panel>
And the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
UserImg.Attributes.Add("onmouseover", "javascript:OnHover(this)");
}
protected void imageHoverTrigger_Click(object sender, EventArgs args)
{
// Hide loading image/label
loadingLbl.Visible = false;
loadingImg.Visible = false;
//TODO: Set user data here
UserInfo.Visible = true;
}
Figured it out:
My Page_Load event hookup should've been:
UserImg.Attributes.Add("onmouseover", "javascript:OnHover('" + this.imageHoverTrigger.UniqueID + "','" + this.hiddenLbl.ClientID + "')");
UserImg.Attributes.Add("onmouseout", "javascript:ClearTimer()");
and the javascript function should've been:
var hoverTimer;
// Called on the hover of the user image
function OnHover(trigger, hiddenTxt) {
var field = document.getElementById(hiddenTxt);
// Only post if this hover hasn't been done before
if (field == null || field.innerHTML == "false") {
hoverTimer = setTimeout(function() { ShowInfo(trigger) }, 500);
}
}
// Clears timeout onmouseout
function ClearTimer() {
clearTimeout(hoverTimer);
}
// Retrieves user info from server
function ShowInfo(trigger) {
__doPostBack(trigger, '');
}
I also added a hidden field on the form in order to know when the hover has been executed. The code behind sets the hidden field to true and my javascript checks for the value of the hidden field each time it executes. This stops the code from doing round trips each time the user hovers over the image.

Categories