Use HtmlEncode in Details View TemplateItem Control - asp.net

I have details view control in my asp.net web form, which on of its item template gets it is value from database, and show this into a richtextbox :
<FTB:FreeTextBox id="txtDescription" runat="Server" AllowHtmlMode="false" Text='<%# (Eval("Description") )%>'
>
</FTB:FreeTextBox>
but when i click on insert or update button, i get the following error :
A potentially dangerous Request.Form value was detected from the client ....
i tried this :
Text='<%# HttpUtility.HtmlDecode((string)Eval("Description"))%>'
bu it did not work ethier, and i got the error again.
is there any way except turning validateRequest off.
Would you please help me?

No, there isn't a way to get this to work aside from turning Validate Request off. Which isn't a bad thing if you write your database functionality correctly and implement strict custom form validation.

Related

EnableViewState="false" does not work and Why asp.net view sate automatically decoded and stored in browser

I used asp.net text-box and set
EnableViewState="false"
then i run my code and enter some sample texts and i enforced the post-back (which means click the button )then Textbox control retain the value .
what i am wrong in my code ?
How can i disable view-state ?
<asp:TextBox ID="TextBox1" EnableViewState="false" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Then i have another one doubt.
Why asp.net view sate automatically decoded and stored in browser. I read some articles the article says it’s a security purpose.
The user gives her/his information and he will use the particular browser and maintain the browser then why view sate is encoded. Is another reasons to decode the view state ?
Well regarding your first question this can be confusing at the beginning. Textbox are simply classes that implement the IPostBackDataHandler interface.
A nice explation can be found here-- http://www.codeproject.com/Articles/378180/View-State-for-TextBox-and-other-controls-that-imp
Regarding your second question about the encryption of viewstate, then you must know the user accessing the page is not only one who can view the viewstate. Pages are posted back on un encrypted channels also, so any body looking over the wire has access to it. Also the user can never be trusted.
My advice to you is to get in details about the view state on msdn. It will help you in long run.

Server side validation

I am having an issue with the requiredfieldvalidator control not working on an ASP.net page. I have completed the attributes of that field properly, but when I test it, the postback is allowed to happen even if the field in question is blank.
So I want to do server side validation instead. What is the best way to do that? In the event that caused the postback? Also, if I find out the field is blank, how do I get the user back to the screen with all other values they placed on other fields intact and a message saying "This field cannot be blank".
EDIT:
This is the code:
<asp:TextBox ID="fName" TabIndex="1" runat="server" Width="221px" CausesValidation="True"></asp:TextBox>
<asp:RequiredFieldValidator ID="FNameRequiredFieldValidator" runat="server" ControlToValidate="fName" InitialValue="" ErrorMessage="Filter Name cannot be blank." ToolTip="Filter Name cannot be blank.">*</asp:RequiredFieldValidator>
You need to provide the markup for your Button / Link control as well.
The 'CausesValidation' attribute is not supposed to be used on TextBox controls.
The button you click needs to have that attribute set to "True".
Please provide that markup and then I can advise on the alternate server side validation.
To enable Client-side Validation, set the EnableClientScript="true" on the RequiredFieldValidator.
You should also always validate on the server side too. But the RequiredFieldValidator doesn't let you do any special-handling server-side. Just check if Page.IsValid(). This will return false if the field is not supplied.
If you want to do custom validation, use a CustomValidator.

Microsoft ReportViewer control (Web) & displaying error messages

I have a Microsoft ReportViewer control on my web page. However, if someone types in an invalid input for one of the parameters then it displays a rather unfriendly error message where the report should go. For example: The value provided for the report parameter 'pToDate' is not valid for its type. (rsReportParameterTypeMismatch)
The control prompts the user for the information with "To Date" and "pToDate" is the internal name of the parameter. The users won't know this, nor will they likely react well to "rsReportParameterTypeMismatch" (what ever that means!? [while thinking like a user])
As I couldn't find somewhere in the ReportViewer control to put any error or custom message, my solution was to create a label in which to put a more friendly error message. This works insofar as the friendly error message is displayed.
My problem is that once the user has corrected their mistake and clicks "View Report" the report is displayed but the error message is still visible. I've set the label text to string.Empty, I've set the label to Visible = false. I've tried this in various places, ensured the code is hit, but to no avail.
So, is there any way to get custom messages to appear and disappear with a ReportViewer control?
Okay - I've got something that works
Previous I had this:
<asp:Label runat="server" ID="ReportErrorMessage" Visible="false" CssClass="report-error-message">
</asp:Label>
which I was updating in the code behind like this:
ReportErrorMessage.Text = GetErrorMessage(reportException);
ReportErrorMessage.Visible = true;
and then removing like this:
ReportErrorMessage.Visible = false;
ReportErrorMessage.Text = string.Empty;
The latter part didn't work.
I eventually realised that the ReportViewer control is using partial rendering and so wasn't actually changing the label at all (and consdering that, I've still not quite figured out how the initial display actually worked, but anyway...)
The solution was to wrap the label in an update panel like this:
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="ReportErrorMessage" Visible="false" CssClass="report-error-message">
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
UPDATE
I've also added a full explanation onto my blog: Friendly Error Messages with Microsoft Report Viewer

how to check a particular asp.net validation control is valid?

In a web form there are different asp.net validation controls. Is it possible to check a particular validation control is valid ? For example on leaving focus of textbox, first I will check requiredFieldValidatorUserName is valid ? If it is valid then I will check on server using ajax that this user name is not booked already.
Edit:
Explaination: I want to check validity (that input was valid) of a validation control on client side.
Please guide.
All validator controls implement IValidator which contains the IsValid property.
myValidatorControl.IsValid
The best way would be to use a CustomValidator with client side code, as this will display all the error messages, block form submission and also ensure that the validation is repeated at the server side - remember, just because you have client-side validation available, doesn't mean the user's seen it: Always validate your input at the server as well.
Your CustomValidator would then be coded to call the Ajax methods, and would show the error messages correctly to the client:
<asp:Label ID="UserNameLabel" AssociatedControlID="UserName" runat="server">
UserName *:</asp:Label>
<asp:TextBox ID="UserName" runat="server" />
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server"
ControlToValidate="UserName" EnableClientScript="true"
ErrorMessage="You must supply a username!" />
<asp:CustomValidator ID="UserNameCustom" runat="server"
ControlToValidate="UserName"
ClientValidationFunction="CheckExisting"
OnServerValidate="UserNameCustomValidate"
ErrorMessage="Username already taken" />
And your ClientValidationFunction should look something like:
<script type="text/javascript">
function CheckExisting(source, arguments) {
// Pass the arguments.Value to your AJAX call:
if (ajaxCallUserNameTaken(arguments.Value)) {
arguments.IsValid = false;
}
}
</script>
(Obviously, you'll need to write the ajaxCallUserNameTaken method to call your page method/web service/etc.)
Doing it this way will ensure that the validation methods happen as expected; this will get called whenever the user tabs out of the textbox leaving a value (it won't get called if the textbox is empty), and will ensure that the user can't submit the page until they supply a unique value. You'll also want to create the method referenced in OnServerValidate to ensure that the value's good once it hits the server too - this should call the same code that the AJAX endpoint uses to reduce duplication of code, etc.
I was originally going to suggest that you could use the Page_Validators object on the client-side to do some checking in the onBlur event, but I don't really think this is suitable here as it results in more pain:
It assumes that although there might be more than one validator on the page, there's only the RequiredFieldValidator on the control we're checking
The RequiredFieldValidator isn't fired during OnBlur if a user moves out of a control without setting a value - only if they set and clear the value, so even if isvalid is true, you need to check for an empty string!
You could do this by setting the ValidationGroup for the Validator control that you want to treat as separate from the others. Make sure it matches the ValidationGroup of the control it's validating (your username field).
I have just faced the same issue and I Set CausesValidation="true" to the textbox control and it worked. Just give it a try :)
I have been messing around with this around for a bit and found a rather easy (not so efficient) solution to handle this using jQuery.
Use this function to check the validity of your control:
function validateControl() {
return $('#YOUR_VALIDATOR_ID').css("visibility") == "visible"
if you're using Display="Dynamic" on your validator then the function is like so:
function validateControl() {
return return $('#YOUR_VALIDATOR_ID').css("display") == "inline"
Be sure to check the true ID of your validator if you're using a Masterpage, as it will be different than the one in your IDE. Do so by viewing the page source in your browser.
The best solution will be of course to validate your form in some other way, using JavaScript or a CustomValidator that lets you write your own code.

asp.net sanitizing user input

Does asp.net have a built in mechanism that can sanitize all textbox input instead of redirecting to the error page?
I have a textbox input where a user can enter a name, but if they try to enter and <> tags the page automatically throws an error. I just want to handle this error in a user friendly way.
You'll want to look at the AntiXSS library for that. It's a dll so it's easy to drop in and start using it.
The download is at CodePlex.
You can use the ASP.NET RegularExpressionValidator control with a pattern like: ^[^<>]*$
<asp:RegularExpressionValidator ID="rev" runat="server"
ControlToValidate="txtBox"
ErrorMessage="The <> tags are not allowed!"
ValidationExpression="[^<>]*" />
<asp:RequiredFieldValidator ID="rfv" runat="server" ControlToValidate="txtBox"
ErrorMessage="Value can't be empty" />
The RequiredFieldValidator is used in conjunction with the RegularExpressionValidator to prevent blank entries. If that textbox is optional, and only needs to be validated when something is entered, then you don't have to use the RequiredFieldValidator.
The benefit of doing it this way is that the error can be handled gracefully and the user can be notified on the same page.
However, if you need to do this for many textboxes and you just want to present something nicer than the error page, you could handle the ValidateRequest error to provide a friendlier message and keep the user on the same page (not just replace it with a custom error page). For more info, check out Kirk Evans' post: Handling ValidateRequest errors within a Page (refer to the section titled Overriding the OnError Method).
Read this for a step-by-step: http://yourtahir.wordpress.com/2008/03/28/aspnet-not-allow-html-in-text-boxserver-error-in-application-a-potentialy-dangerous-requestform-value-was-detected/
You have to do some web.config work.
ASP.net has validation controls
[http://msdn.microsoft.com/en-us/library/7kh55542.aspx][1]
Also there is Mark Down Editor which is a control that strips out html tags etc.

Resources