When i upload a file to my server i have the codebehind check for several illegal situations, and then i set the text of an asp:label to display the error if one occurs.
The problem is that the file upload posts back even when the if statement fails and an error is written to the label, thus resetting the page to its original state and resetting the message label.
Edit and Update
After accepting that the postback would occur i loaded the error messages into a session variable and on post back checked that variable for an error rand updated the asp:list to show the error message.
The line that updated the asp:label had to be placed into a PreRender event as the Load event happened before the postback had processed. causing the page to have to postback twice to show the message.
U hope this helps anyone. Additionally as mentioned below reading through the ASP Page Life Cycle will do wonders
I would suggest checking out the very comprehensive MSDN article about Validating ASP.NET Server Controls. Basically, you will be adding to your front end the following: asp:ValidationSummary, and asp:CustomValidator with back-end code that handles the "illegal check" and then sets the page IsValid to true or false, depending on the outcome of the customer validate function in the code-behind.
An example on SO here: How to Add Error Message to Validation Summary
Related
Joined a company that use Asp.Net, a tech that I had never worked with before. I have a very simple task to do which is to change a label's text depending on a value that is included in the logged in user's session.
I considered Init, Page Load and PreRender and ended up placing my code in the PreRender event and got a comment in a code review from the main code reviewer saying "this does not belong here, go and investigate the page lifecycle to figure out why"
According to the docs:
Init should be used to "initialize control properties" (which seems to be about right for this case).
Page Load should be used to "set properties in controls and to establish DB connections".
PreRender should be used to "make the final changes to the page or its controls"
I can't see an obvious event that should be used instead of the others. I wrote above that Asp.Net is new to me so I may be missing something.
Which event should be used in this particular case, and in general, to change properties of controls?
I am trying to upload image files using html editor extender. Everything works fine so far and I am able to save the file on ImageUploadComplete event. But I am not sure how to raise the error to UI and alert user if the image upload fails for some reason.
Your help would be very much appreciated. Thanks!
Update: We use MS enterprise library for exception handling. In normal postback errors, the exception gets logged first and would get redirected to the custom error page. The issues with using HTMLEditorExtender are:
redirect on error is NOT working
fileupload control is showing wrong upload status - "Uploaded" even in case of failures.
Public Sub HTMLEditor_ImageUploadComplete(sender As Object,
e As AjaxControlToolkit.AjaxFileUploadEventArgs)
Handles HTMLEditor.ImageUploadComplete
HTMLEditor.AjaxFileUpload.SaveAs("D:\Uploads\" + Path.GetFileName(e.FileName))
End Sub
Since this is a server-side control you should be able to report errors like you would server-side for anything else (i.e. ASP.NET Label control with red forecolor and invisible until an error occurs), like this:
<asp:Label id="ErrorLabel" runat="server" ForeColor="Red" Visible="False"/>
Then on the method referenced in your OnImageUploadComplete attribute of the extender control you can direct error information to this error label control.
You can simply throw an exception and it will show as failed upload in the AjaxFileUpload box used by the HtmlEditorExtender.
If you want to handle the error yourself, you would either need to use the OnClientUploadError client side event of the AjaxFileUpload or download the AjaxControlToolkit source code and edit it to work as you need.
If your environment is unable to respond with and error HTTP Status then you can manually respond using Context.Response.Write() and write the appropriate JSON that the AjaxFileUpload expects. And then handle its client side events accordingly.
i have just noticed something strange in some asp.net markup.
I have a standard form with a couple of textboxes and a submit button.
When clicked the code behind will attempt to perform some logic and then return.
If the input values are not valid it used to throw an exception.
The moment i wrapped the controls in an AJAX update panel and try to submit bad data, no exception is thrown and the panel returns like nothing was wrong.
Does anyone know how to return this to the previous behavior whilst keeping the update panel?
The expression it is thrown, but its handle by ajax, and now have be come Javascript errors, because now the full page is not loaded, but the error return back from javascript ajax call.
To see them just open your javascript error console :), how ever you do not need the expression as Raj say, you need to find other way to show your errors.
When I won to make some test and find my error, I remove the Ajax Panel for this reason, locate the error, fix them, then place back the Ajax Panel
I am getting the error: "Invalid postback or callback argument. Event validation is enabled using in configuration or 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." Event validation is enabled using in configuration or in a page. I am not modifying the data in controls through javascript. The error happens very infrequently and I am only aware of it due to some automatic e-mailing I have setup when exceptions are thrown. What is the best way for me to go about finding the cause of the exception? Is it possible that on occasions some text entered into a text box is causing this error and I need to be doing an Html Encode? When would I do the encode?
If the problem happens very infrequently it usually means that some user has posted a page to quickly or have a very poor connection, that does not allow all the hidden ASP.net callback javascript mechanism being in place.
I've often encountered this issue when a user submits a form with a potentially dangerous character in the field ('<', '>', etc.). If your page needs to allow these characters to be submitted in a form, you need to set the page-level property 'ValidateRequest' to false.
Ex.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="MyClass.cs" Inherits="MyClass" ValidateRequest="false" %>
If you want to block these types of submissions (which is usually advisable), you'll probably need to add client-side scripting to prevent entry of invalid characters to the form. If the user can't enter the invalid values, then the form can post successfully. If you try to do the validation only on the server-side, it won't be run because the .NET ValidateRequest happens first.
I've had this error before, it turned out someone had changed the "action" attribute of the form runat="server" tag to a different url (which doesn't work unless using cross page postbacks).
-edit: in this case ofcourse it doesn't happen infrequently, so it's probably not going to help you to the right solution
I just added asp.net calendar control in new page under sample folder in asp.net mvc beta application. when i execute the particaular page that i need and it shows the error following
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
that points to here . It's in site.master of asp.net mvc
<div id="logindisplay">
<% Html.RenderPartial("LoginUserControl"); %>
</div>
usually to avoid this error, we give
<pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" >
but, it doesn't work for me.
Before reading further, please exclude the following preconditions:
You aren't using a web farm.
It appears when using built-in databound controls such as GridView, DetailsView or FormView which utilize “DataKeyNames”.
It appears if you have a large page which loads slowly for any reason.
If following preconditions are true and you click a postbacking control/link and the page hasn't loaded completely in client browser, you might get the "Validation of ViewState MAC failed" exception.
When this happens, if you just try setting the page property "EnableViewStateMac" to false, it does not solve the problem, it just changes the error message in same navigation behavior:
The state information is invalid for this page and might be corrupted.
This exception appears because Controls using DataKeyNames require Viewstate to be encrypted. When Viewstate is encrypted (Default mode, Auto, is to encrypt if controls require that, otherwise not), Page adds field just before closing of the <form> tag. But this hidden field might not have been rendered to the browser with long-running pages, and if you make a postback before it does, the browser initiates postback without this field (in form post collection). End result is that if this field is omitted on postback, the page doesn't know that Viewstate is encrypted and causes the aforementioned Exception. I.E. page expects to be fully-loaded before you make a postback.
And by the way similar problem is with event validation since __EVENTVALIDATION field is also rendered on the end of the form. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered <form> tag, you'll see something like this: . When a postback occurs, ASP.NET uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception above.
The problem happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.NET cannot validate your click.
Workaround
Set enableEventValidation to false and viewStateEncryptionMode to Never as follows:
<pages enableeventvalidation="false" viewstateencryptionmode="Never">
This has the unwanted side-effect of disabling validation and encryption. On some sites, this may be ok to do, but it isn't a best practice, especially in publicly facing sites.
For more information and other workaround see this blog entry.
This happened to me just a few minutes ago. Luckily, I found this blog post on the subject. The upshot (for me, at least), was that I had two forms, one on the page and one on the control.
I didn't need the one on the page, so I removed it, and the error went away.
I have been struggling with this issue too since lasts few days and finally found the problem.
This error will show up in there are multiple <form> tags are being rendered on a page (be it html <form></form> or Html.BeginForm()).
Check the user controls being rendered, the content page section and also the Master page.
Make sure there is only one form rendered on a page.
This should fix your problem, if the issue persists, check for the for submit buttons rendered on the page (<input type="submit" …/>)
Cheers!
Mayank Srivastava