Reasons Why Custom Validator May Not Be Showing Error Msg? - c#

Unfortunately I can't show you the code so I am just going to have to explain the problem.
I have a detail view that is in a update panel. I added a custom validator that should appear open the condition if Radio Button A is selected TextBox A must have a value in it.
I setup an OnServerValidate method that checked for this and if it fails then I set args.Valid to false.
However my error message never appears. If I look through IE Developer Tool I see my customer validator with the hard coded message but it is hidden(visibility: hidden).
I tried to find the customvalidator and force visibility to show and even went as far to try to remove it through customValidator.Style.Remove("visibility") yet nothing works. The message is always hidden.
The page does fail validation as if that condition is met my page won't save. It just won't show my message that I set in custom validator.
Edit
I also tried doing Visible="true" in the aspx code of the custom validator and it stil will not show the error msg and in developer toolkit shows it as hidden.

Same problem here. I tried everything, changing the style attribute on the validator, using Javascript to change the style, Jquery, etc. Nothing would work, its style was always "visibility:hidden".
Eventually I ended up doing the most ridiculous workaround by just adding a label with my error message:
<asp:Label ID="ErrorLabel" runat="server" Visible="False" CssClass="validator-red">
Error message here
</asp:Label>
and manually displaying it in the validation event handler:
protected void Validator_ServerValidate(object source, ServerValidateEventArgs args) {
// Validation code, set args.IsValid here.
ErrorLabel.Visible = !args.IsValid;
}
That's functionality that's meant to be included with all validators, but it looks like MS stuffed it up on this one. At least this works reliably. Also don't forget to set Display="None" on the validator as you won't be needing that.

I ran into a similar problem myself and found this thread, just before I found an answer...not sure if it's still worthwhile, but here's what I did.
1) I added the following (VB.net code, but you should be able to port it to C#):
My_Custom_Validator.Attributes.Add("class", "invalid")
2) I created a CSS invalid class rule:
.invalid {display: block !important; visibility: visible !important;}
The !important will override the inline CSS created by the .NET code. Setting it on display: block; isn't necessary, but I put it just in case.
This doesn't answer your question as to why the visibility: hidden; inline CSS appears...it's just a workaround.

Related

Asp.net maintainScrollPositionOnPostBack and forms validation fail

I have a very long form that has to be filled out. I have maintainScrollPositionOnPostBack enabled as I have multiple controls that hide/show based on user input.
Since the form is long I'd like for the page to focus and scroll to the first control that caused validation to fail and I have the focus on validation fail option enabled. However, it seems that maintainScrollPositionOnPostBack overrides this (the control does focus but doesn't scroll up to it).
Any ideas for workarounds for this? Everything I've tried so far hasn't worked. It is an asp.net webforms project.
This is a good question and really tricky to get working. But I managed to get one version that you can try and maybe build on.
The MaintainScrollPositionOnPostback="true" -setting sets a series of javascript-events on form submit and window load and these do as you say, "overwrite" the focus set by the validator.
So what I did was add a common css-class to all validators like so:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" CssClass="error" ErrorMessage="RequiredFieldValidator" SetFocusOnError="true"
EnableClientScript="false" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
And then I added another eventlistener to window.load (note we need to leave also the one that Asp.Net has added so we cannot do windows.load = function...):
<script>
window.addEventListener("load", function () {
var el = document.getElementsByClassName("error");
if (el.length > 0) {
window.location.hash = "#" + el[0].id;
}
});
</script>
Here you might benefit from jQuery use to be able to support more browsers but addEventListener is pretty well supported.
The script searches for the errormessage and focus on that by it's id with anchor. Javascript has focus-method but it's for form elements so that's why this workaround.
Hope this helps!

How can I make a RequiredFieldValidator trigger a message elsewhere on the page?

I have a page with a repeater containing RadioButtonLists which have requiredFieldValidators attached to them. I need to keep the RFV next to the control (it's the only way I can get it to work to be honest!)
However, the form is made up of a few sections contained in an accordion. This means that when the form is submitted, the item that has failed validation may not be visible, so the user won't know where the error is.
Is there a way I can also have a message by the submit button which is triggered by an RFV changing saying "please go back and check your answers" or something? I guess I'd need to use JQuery / JavaScript as it would be clientside.
There is a special ValidationSummary control for that:
<asp:ValidationSummary ID="Summary" runat="server"
DisplayMode="SingleParagraph"
HeaderText="Please go back and check your answers" />
This control is used to summarize all validation errors on the page.
Try "ValidationSummary". look for example from here.
http://www.w3schools.com/aspnet/control_validationsummary.asp

AjaxControlToolKit HTMLEditorExtender adding anchor tag as a normal text when a link is added

I am unable to write a nice title to this topic because my problem is a little weird. I am using AjaxControlToolkit HTMLEditorExtender in my website to send HTML formatted emails. Every other feature like bold, italic, underline etc. are working fine but when I add a link it shows the HTML code of it as follows:
As you can see BOLD is working but the anchor tag is appearing in HTML code format.
Code for extender and the textbox:
<asp:TextBox ID="TextBox2" runat="server" Height="376px"
TextMode="MultiLine" Width="795px"></asp:TextBox>
<asp2:HtmlEditorExtender ID="TextBox2_HtmlEditorExtender"
runat="server" Enabled="True" TargetControlID="TextBox2">
</asp2:HtmlEditorExtender>
Can any one please tell me why this is happening? Is this some bug with the extender?
Considering I do not have enough reputation for commenting on the post, I will ask a followup question here. Is there any way we could see the text you are getting on your C# backend? This is a possible source for the issue if the string has some weird formatting.
Plus email clients are not meant to be browsers and there is a possibility that the email client will not render the html correctly.
Is that image a screen shot of the editor itself? I created my own test project using your same code.
Also, how did you create the link? I typed some text highlighted the text and clicked on the 'create link' icon and from there I typed in the URL. It created the link as expected.
The only difference is that I didn't bother implementing a sanitizer, which it appears you did. I would try disabling the sanitizer (just for testing purposes) and see if that's where your problem lies.
Try this it should solve your issue-
txtEmialMsg.Text=Server.HtmlDecode(ActualStringFromExtender.ToString());
Or if you are getting (A href) text then you need to use following when sending emails
Server.UrlDecode(link)

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server."

I have couple of update panels and jquery tabs on page. And also I am loading couple user controls on update panels. After user waited for couple of minutes (not checked the time approx 40 mins). when user send request from submit button it is giving below error?
'Sys.WebForms.PageRequestManagerServerErrorException:
Sys.WebForms.PageRequestManagerServerErrorException: An unknown
error occurred while processing the request on the server. The status
code returned from the server was: 0' when calling method:
[nsIDOMEventListener::handleEvent]
I am not able trace this issue to fix. But I am sure. This is causing by Ajax. Gurus, if you knows solution. Please let me know.
This issue sometimes occurs when you have a control registered as an AsyncPostbackTrigger in multiple update panels.
If that's not the problem, try adding the following right after the script manager declaration, which I found in this post by manowar83, which copies and slightly modifies this post by larryw:
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args){
if (args.get_error() != undefined){
args.set_errorHandled(true);
}
}
</script>
There are a few more solutions discussed here: http://forums.asp.net/t/1066976.aspx/9/10
I had this issue and I spent hours trying to fix it.
The solution ticked as answered will not fix the error only handle it.
The best approach is to check the IIS log files and the error should be there. It appears that the update panel encapsulates the real error and outputs it as a 'javascript error'.
For instance my error was that I forgot to make a class [Serializable]. Although this worked fine locally it did not work when deployed on the server.
I got this error when I had my button in the GridView in an UpdatePanel... deubbing my code I found that the above error is caused because of another internal error "A potentially dangerous Request.Form value was detected from the client"
Finally I figured out that one of my TextBoxes on the page has XML/HTML content and this in-turn causing above error
when I removed the xml/HTML and tested the button click ... it worked as expected.
I have got the same issue, here I give my problem and my solution hoping this would help someone:
Following other people recommendation I went to the log of the server (Windows Server 2012 in my case) in :
Control Panel -> Administrative Tools -> Event Viewer
Then in the left side:
Windows Logs -> Application:
In the warnings I found the message from my site and in my case it was due to a null reference:
*Exception type: NullReferenceException
Exception message: Object reference not set to an instance of an object.*
And checking at the function described in the log I found a non initialized object and that was it.
So it could be a null reference exception in the code.
Hope someone find this useful, greetings.
Brother this piece of code is not a solution just change it to
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args){
if (args.get_error() != undefined){
**alert(args.get_error().message.substr(args.get_error().name.length + 2));**
args.set_errorHandled(true);
}
}
</script>
and you will see the error is there but you are just not throwing it on UI.
This solution is helpful too:
Add validateRequest="false" in the <%# Page directive.
This is because ASP.net examines input from the browser for dangerous values. More info in this link
I also faced the same issue , and none of these worked. In my case this was fixed by adding these lines in config file.
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="100000" />
</appSettings>
<system.web.extensions>
<scripting>
<scriptResourceHandler enableCompression="false" enableCaching="true"/>
</scripting>
</system.web.extensions>
This is not the real problem, if you want to see why this is happening then please go to error log file of IIS.
in case of visual studio kindly navigate to:
C:\Users\User\Documents\IISExpress\TraceLogFiles\[your project name]\.
arrange file here in datewise descending and then open very first file.
it will look like:
now scroll down to bottom to see the GENERAL_RESPONSE_ENTITY_BUFFER
it is the actual problem. now solve it the above problem will solve automatically.
For those using the internal IIS of Visual Studio, try the following:
Generate the error message.
Break the debugger at the error display.
Check the callstack. You should see 'raise'.
Double click 'raise'.
Check the internals of 'sender' parameter. You will see a '_xmlHttpRequest' property.
Open the '_xmlHttpRequest' property, and you'll see a 'response' property.
The 'response' property will have the actual message.
I hope this helps someone out there!
Check your Application Event Log - my issue was Telerik RadCompression HTTP Module which I disabled in the Web.config.
#JS5 , I also faced the same issue as you: ImageButton causing exceptions inside UpdatePanel only on production server and IE. After some research I found this:
There is an issue with ImageButtons and UpdatePanels. The update to
.NET 4.5 is fixed there. It has something to do with Microsoft
changed the x,y axis of a button click from Int to Double so you can
tell where on the button you clicked and it's throwing a conversion
error.
Source
I'm using NetFramework 2.0 and IIS 6, so, the suggested solution was to downgrade IE compatibility adding a meta tag:
<meta http-equiv="X-UA-Compatible" content="IE=9" />
I've done this via Page_Load method only on the page I needed to:
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim tag As HtmlMeta = New HtmlMeta()
tag.HttpEquiv = "X-UA-Compatible"
tag.Content = "IE=9"
Header.Controls.Add(tag)
End Sub
Hope this helps someone.
I had the same issue, when i was trying out a way to solve it, i found out that the update panel was causing this issue. Depending on my requirement i could remove the update panel and get rid of the issue.
So it's a possible solution for the issue.
We also faced the same issue, and the problem could only be reproduced in the server (i.e., not locally, which made it even harder to fix, because we could not debug the application), and when using IE. We had a page with an update panel, and within this update panel a modalpopupextender, which also contained an update panel. After trying several solutions that did not work, we fix it by replacing every imagebutton within the modalpopupextender with a linkbutton, and within it the image needed.
Use the following code below inside updatepanel.
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args){
if (args.get_error() != undefined){
args.set_errorHandled(true);
}
}
</script>
For me the problem was that I was using a <button> instead of a <asp:LinkButton>
Some times due to some code you get HTML tags in a text filed, like I was replacing some characters with new line BR tag of HTML and by mistake I also replaced it in the text that was supposed to be displayed in a Multiline text box so my multiline text box had a new line HTML tag BR in it coming dynamically due to my string replace function and I started getting this JavaScript error and as this HTML code was displayed in a text box that was in an update panel I start getting this error so I made the correction and all was fine. So before copying pasting anything please look at your code and see that all tag are closed proper and no irrelevant code data is coming to text boxes or Drop down lists. This error always come due to ill formed tags and irrelevant data.
My fix for this was to remove any HTML markup that was in the Text="" property of a TextBox in my asp.net code, inside an update panel. If you have more than one update panel on a page, it will affect them all, which makes it harder to work out which panel has the issue. Chris's answer above lead me to find this, but his is a very hidden answer but I think a very relevant one so here is an answer explained.
<asp:TextBox ID="bookingTBox" runat="server" ToolTip="" Width="150px" Text="<Auto Assigned>" CssClass="textboxItalicFormat"></asp:TextBox>
The above code will give this error.
The below will not.
<asp:TextBox ID="bookingTBox" runat="server" ToolTip="" Width="150px" Text="Auto Assigned" CssClass="textboxItalicFormat"></asp:TextBox>
In the second textbox code I have removed the < and > from the Text="" property. Please try this before spending time adding lines of script code, etc.
Had this problem when using AsyncFileUploader in an iFrame. Error came when using firefox. Worked in chrome just fine. It seemed like either the parent page or iframe page was loading out of sync and the parent page could not find the controls on the iframe page. Added a simple javascript alert to say that the file was uploaded. This gave the controls enough time to load and since the controls were available, everything loaded without an error.
I had this issue when I upgraded my project to 4.5 framework and the GridView had Empty Data Template. Something changed and the following statement which previously was returning the Empty Data Template was now returning the Header Row.
GridViewRow dr = (GridViewRow)this.grdViewRoleMembership.Controls[0].Controls[0];
I changed it to below and the error went away and the GridView started working as expected.
GridViewRow dr = (GridViewRow)this.grdViewRoleMembership.Controls[0].Controls[1];
I hope this helps someone.
This issue for me was caused by a database mapping error.
I attempted to use a select() call on a datasource with errors in the code behind. My controls were within an update panel and the actual cause was hidden.
Usually, if you can temporarily remove the update panel, asp.net will return a more useful error message.
" 1- Go to the web.config of your application "
" 2- Add a new entry under < system.web > "
3- Also Find the pages tag and set validateRequest=False
Only this works for me. !!
Be sure to put tilde and forward slash(~/) when CDN is the root directory. I think it's an issue in IIS
as my friend #RaviKumar mentioned above one reason of following problem is that some piece of data transferred from code to UI contain raw html tags which make request invalid for example I had a textarea and in my code I had set its value by code below
txtAgreement.Text = Data.Agreement
And when I compiled the page I could see raw html tag inside textarea so I changed textarea to div on which innerhtml works and render html (instead of injecting raw html tags into element) and it worked for me
happy coding
<add key="aspnet:MaxHttpCollectionKeys" value="100000"/ >
Add above key to Web.config or App.config to remove this error.
I got this error when I had ModalPopupExtender in the update panel... deubbing my code I found that the above error is caused because of updatepanel updatemode is conditional... so i change it to always then problem is solved.
This was working fine in my code.. i solved my issue.. really
Add below code in web.config file.
<system.web>
<httpRuntime executionTimeout="999" maxRequestLength="2097151"/>
</system.web>
answer for me was to fix a gridview control which contained a template field that had a dropdownlist which was loaded with a monstrous amount of selectable items- i replaced the DDL with a label field whose data is generated from a function. (i was originally going to allow gridview editing, but have switched to allowing edits on a separate panel displaying the DDL for that field for just that record). hope this might help someone.
This error: Uncaught Sys.WebForms.PageRequestManagerServerErrorException ....
i got in backend logic of one UpdatePanel when Oracle made exception because of mispelled column/table in sql command....

ASP.NET button options.clientSubmit is set to false

I have a ASP.NET button which sometimes does not post back. I checked this in IE developer and found that when the button does not work options.clientSubmit is set to false in the function WebForm_DoPostBackWithOptions()
My button code
<asp:Button
runat="server"
ID="btnSubmit"
CssClass="button"
OnClick="btnSubmit_Click"
meta:resourcekey="btnSubmitResource1" />
Inside WebForm_DoPostBackWithOptions(options)
if (options.clientSubmit) {
__doPostBack(options.eventTarget, options.eventArgument);
}
Can anyone tell me why the button sometimes works and sometimes does not? what should I do to make it work always?
This may be a possibility:
Check if you have any Validators on the page which have not been grouped to any ValidationGroup and may be visible false(may be due container is visible false). This validator may be validating the control which is of no relevance under this circumstance and causing the postback to cancel saying it invalid.
If you find any, to group all the related controls, assign a ValidationGroup to all the corresponding Validators and then assign that group to your submit control(whichever causes postback). This is most common mistake I have seen..
Try adding CausesValidation = "False" and see what happens. I suspect you have some validation that isn't passing.
You're not using anything to prevent repeated submission of the form?
I had exactly the same issue, the .Net validation method indicated that the form was valid, but options.clientSubmit was always false :S
The culprit turned out to be:
<script type="text/javascript">
$(document).ready(function() {
$('.prevDblSubmit').preventDoubleSubmit();
})
</script>
This seems that should be working, instead of using meta:resourcekey="btnSubmitResource1", try explicit localization. See question: ASP.NET: explicit vs implicit localization?

Categories

Resources