Why I can't access to my own User Control? - c#

Following this guideline, I've created my own User Control and registered into the webconfig:
public partial class usercontrols_LinkBoxAttivita : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public int MyProp { get; set; }
}
On Home.ascx I've included this:
<myOwnControls:LinkBoxAttivita ID="LinkBoxAttivita1" runat="server" />
It works, and it is rendered. Now, why on the codebehind of Home.ascx.cs I can't access to it?
LinkBoxAttivita1 seems unexistent. I want to set from here the MyProp value to it.
This is how I registered it:
<system.web>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
<controls>
<add tagPrefix="myOwnControls" tagName="LinkBoxAttivita" src="~/usercontrols/LinkBoxAttivita.ascx" />
</controls>
</pages>
</system.web>

Have you dragged the UserControl to the designer? Otherwise the designer won't create the #Register directive, which is required for the page to recognize the user control.
How to: Include a User Control in an ASP.NET Web Page
Example (from MSDN):
<%# Page Language="C#" %>
<%# Register TagPrefix="uc" TagName="Spinner"
Src="~/Controls/Spinner.ascx" %>
<html>
<body>
<form runat="server">
<uc:Spinner id="Spinner1"
runat="server"
MinValue="1"
MaxValue="10" />
</form>
</body>

Related

Can not disable ViewState

I have made a simple Web Form where I try to get rid of the ViewState. When I run it and press Go the label gets the value of whatever I put in the texbox. So far all good. But the textbox maintains the value I filled in. As far as I understand it this is done by the ViewState mechanism. What do I miss?
<%# Page Language="C#" AutoEventWireup="true" Inherits="SportsPlay.Sida1" ViewStateMode="Disabled" EnableViewState="false" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server" enableviewstate="false">
<div>
<asp:TextBox runat="server" ID="txtTest" ></asp:TextBox>
<asp:Button runat="server" ID="btnGo" Text="Go" OnCommand="btnGo_Command" />
<asp:Label runat="server" ID="lblResult"></asp:Label>
</div>
</form>
</body>
</html>
<script runat="server" language="C#">
void btnGo_Command(object sender, CommandEventArgs e)
{
lblResult.Text =txtTest.Text ;
}
</script>
Aside from the previous answer you can explicitly clear it on click TextBox1.Text = ""; Or Redirect to the same page should clear everything out.
The ViewState manages the information of the current page. It is utilized by the HTML pages by ASP.NET applications to maintain the state of the web form controls. By this you can save a lot of coding by maintaining the ViewState of the objects in your Web Form.
You do not need ViewState in the following situations:
The control is repopulated on every postback. If you ignore old data, and if you repopulate the server control each time the page is refreshed then you do not need ViewState.
When you complete a web page, review the controls in the page and consider what information is being passed in the view state and whether you really need all that information to be maintained. To optimize web page size, consider disabling view state in these cases.
The control is an input control and it changes only from user actions.
The control never changes.
By default, ViewState is enabled for all server controls. ViewState can be enabled and disabled in any of the following ways:
Control Level
Page Level
Application Level
Machine Level
To disable ViewState
To disable ViewState for a single control on a page, set the EnableViewState property of the control to false, as in the following:
<asp:DropDownList ID="DropDownList1" runat="server" EnableViewState="false" />
To disable ViewState for a page
To disable ViewState for a single page, set the EnableViewState attribute in the # Page directive to false, as in the following:
<%# Page Language="C#" EnableViewState="false" AutoEventWireup="true" CodeFile="URLRouting.aspx.cs" Inherits="URL_Rewriting" %>
To disable a page's View State, add the code below in the Page class of the page.
public void DisableViewState()
{
this.Init += new EventHandler(Page_Init);
}
private void Page_Init(object sender, System.EventArgs e)
{
this.EnableViewState = false;
}
To disable ViewState for a specific application
To disable ViewState for a specific application, use the following element in the Web.config file of the application:
<configuration>
<system.web>
<pages enableViewState="false" />
</system.web>
</configuration>
To disable ViewState for all applications on a Web server
To disable ViewState for all applications on a Web server, configure the element in the Machine.config file as follows:
<Machine.config >
<system.web>
<pages enableViewState="true" />
</system.web>
</Machine.config>

Using Tinymce results in Internal server error in asp.net

I am using Tinymce in my web page and in client side every thing works fine. But when I try to access the tinymce textbox in code behind the page control doesnot render. I mean Page load Didn't Render. Here is my HTML Code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="RichText.aspx.cs" Inherits="TESTING.RichText"
ValidateRequest="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Rich Text</title>
<script src="<%=ResolveClientUrl("~/Script/jquery-ui-1.7.1.custom.min.js") %>" type="text/javascript"></script>
<script type="text/javascript" src="Scirpt/tinymce/jscripts/tiny_mce/tiny_mce.js"> </script>
<script type="text/javascript" src="Scirpt/tinymce/jscripts/tiny_mce/InitializeRichTextBox.js"> </script>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 400px">
<div style="height: 100px; width: 100%;">
</div>
<asp:TextBox ID="TextBox1" runat="server" TextMode="multiline" CssClass="RichTextBox"
Width="150px"></asp:TextBox>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
</html>
Here is my Code Behind code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TESTING
{
public partial class RichText : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string here = TextBox1.Text;
}
}
}
When i leave empty text then Page Load renders and when I write something and click on Button then this error occurs A potentially dangerous Request.Form value was detected from the client (TextBox1="<ul><li><em><span ..."). I tried to find the solution in internet but unable to find the solution. Please help me out to find the solution.
Add this in Web.config
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime requestValidationMode="2.0"/>
</system.web>
</configuration>
and add ValidateRequest = "false" in Page directive like this
<%# Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" ValidateRequest="false" %>
for your reference click here

A potentially dangerous Request.Form value was detected from the client

I have this issue. I have tried everything. ValidateRequest="false".. and decoding and encoding html.. etc. etc..
What I need is a popup box (so im using ModalPopupExtender) to present to a user where people can type in xml settings and click ok/cancel button to close the popup and save.
However i keep on getting this error "A potentially dangerous Request.Form value was detected from the client"..
Here is my test code below (quick example of my scenario and error)..
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1"
ValidateRequest="false" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:Panel ID="Popup" runat="server" Width="800px" Style="display: none;">
<asp:LinkButton ID="Display" runat="server" Style="display: none;" OnClick="Display_Click" />
<cc1:ModalPopupExtender ID="ModalPopupExtender" runat="server" TargetControlID="Display"
PopupControlID="Popup" DropShadow="false" Y="10" />
<div id="Item">
<div class="Item">
<table width="100%">
<tr>
<td>
<textarea id="txtAreaValue" cols="35" rows="6" style="resize: none;" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnOk" Text="Ok" SkinID="default" Width="50px" runat="server" />
<asp:Button ID="btnCancel" Text="Cancel" SkinID="default" Width="50px" OnClick="BtnCancel_Click"
runat="server" />
</td>
</tr>
</table>
</div>
</div>
</asp:Panel>
</div>
</form>
</body>
</html>
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ModalPopupExtender.Show();
string str = "<?xml version=\"1.0\" encoding=\"utf-8\"?><XmlConfig xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <XmlConfig Type=\"TEST\" DefiningXpath=\"/PERSON/NAME\"><Index Name=\"Name\" XPath=\"/PERSON/NAME/VALUE\" Type=\"String\" /><Index Name=\"Id\" XPath=\"/PERSON/NAME/ID\" Type=\"String\" /> </XmlConfig></XmlConfig>";
txtAreaValue.InnerText = str;
}
protected void Display_Click(object sender, EventArgs e)
{
//Shows the Item detail Edit box
ModalPopupExtender.Show();
}
protected void BtnCancel_Click(object sender, EventArgs e)
{
ModalPopupExtender.Hide();
}
}
}
To run the code.. Add ref to AjaxControltoolkit.dll and then run and you will see the textarea being populated with xml. Click on the cancel button and this causes the error. Please can anyone help me?
Use
<httpRuntime requestValidationMode="2.0" />
in your web.config (keeping any attributes you already have on that element, if it's already there). ASP.NET4.0 ignores ValidateRequest otherwise.
And, of course, do make sure that you take necessary measures to protect against genuinely dangerous requests, now that it's not being done for you.
Edit: A great way of doing this is to create your own class derived from RequestValidator, and using the 4.0 behaviour, but with that as the class that does the checking.
Here are possible solution which may help you.
Make server side configuration setting for this.
If you want to allow HTML element as input from selected pages in your project than you set this page attribute.
<%# Page ValidateRequest="false" %>
This ValidateRequest="false" on each page.
If you want in all pages in you project than make changes in Web.Config file.
Add this tag In section.
If you are using .Net 4.0 than you have to make one more change in Web.Config file.
Add this tag In section.
<httpRuntime requestValidationMode="2.0" />
Here are configuration for do not validate request for all pages in .Net 4.0
<configuration>
<system.web>
<httpRuntime requestValidationMode="2.0" />
</system.web>
<pages validateRequest="false">
</pages>
</configuration>
Here is full example on this. Click Here...
Well, people are talking about Asp.net 4.0 only... I guess we need to address other versions too. Today, I had the same problem when I replaced my AjaxToolkit editor with TinyMCE and with the postback I found the same issue.
"A potentially dangerous Request.Form value was detected from the client"..
So I used this line inside my webconfig and it worked for me.
<system.web>
<pages validateRequest="false" />
</system.web>
It should work across Asp.net 2.0 to 3.5.
UPDATE: Even works upto .net 4.5
UPDATE: You can also try to validate the request on page level rather whole website. Just wanted to let the readers to choose the best way. Thanks DVD for pointing this out.
I created a table article with columns articleId and article_content. I also used html editor for article_content column. When I tried to save I got the same error. It was resolved by adding [AllowHtml] to the article_content property in the class.
[AllowHtml]
[Required]
public string article_content { get; set; }
Don’t forget to include the namespace using System.Web.Mvc. For more details: http://www.infinetsoft.com/Post/A-potentially-dangerous-Request-Form-value-was-detected-from-the-client/1246
You can use JavaScript to encode the values before sending to the server, if that suits your needs
see this answer
"A potentially dangerous Request.Form value was detected from the client"..
1) set httpRuntime requestValidationMode="2.0" requestPathInvalidCharacters="<,>,\" in web.config file
2) set validateRequest="false" in side pages tag in web.config file
<system.web>
<httpRuntime requestValidationMode="2.0" requestPathInvalidCharacters="<,>,\"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" validateRequest="false"/>
<system.web>
I faced this same problem while sending some email templates from aspx page to code behind....
So I tried to solve this by adding
<httpRuntime requestValidationMode="2.0" />
in my web config under enter code here` but that did not helped me unless I putted
ValidateRequest="false"
attrribute in the page directive of the aspx page.
There are 3 options to remove this error.
Set validateRequest="false" in page directives.
Set validateRequest="false" in web.config file.
Set requestValidationMode="2.0" in web.config if you are using DotNet 4.0
Checkout this link for more info.

ASP.NET Server control error: Unknown server tag

This is my first attempt to build an ASP.NET server control. Writing the control code was simple but I've run into a roadblock trying to get the control on a web page.
I built the control in one project and referenced it in another. In that second project I got the control into the Toolbox and dragged/dropped the control on the page. I can compile the web project without error, but when I browse to the page I get this error:
Parser Error Message: Unknown server tag 'cc1:StandardControl1'.
Doing some looking around I see others having this problem for various reasons, but none seem to apply to my situation. One solution was to add the assembly to the register tag, but that isn't an issue with my page:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="another.aspx.vb" Inherits="Educate.another" %>
<%# Register Assembly="ServerControlSandbox" Namespace="ServerControlSandbox" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<cc1:StandardControl1 runat="server">
</cc1:StandardControl1>
</div>
</form>
</body>
</html>
Another solution said to add it to the web.config, again with the assembly attribute. But with this in my web.config I still get the error:
<controls>
<add tagPrefix="cc1" namespace="ServerControlSandbox" assembly="ServerControlSandbox"/>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
I'm thinking there is something simple I am missing but I see nothing wrong, judging by the examples I've looked at. Does anyone have any ideas? Thanks.
Also, here is the control code:
namespace ServerControlSandbox
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:StandardControl1 runat=server></{0}:StandardControl1>")]
public class StandardControl : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Text
{
get
{
String s = (String)ViewState["Text"];
return ((s == null) ? "[" + this.ID + "]" : s);
}
set
{
ViewState["Text"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
output.Write(Text);
string block = "<p>Here is some text.</p>";
output.Write(block);
}
}
}
Should it just be:
<cc1:StandardControl ID="scSomething" runat="server">
</cc1:StandardControl>

Namespaces in web.config file not working [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to add namespaces in web.config file?
I am trying to add namespace in web.config file, so that I can use it in all web pages (in code behind). But it is not working.
Has anybody tried it ? I have asked this before but not get any suitable answer.
To better understand here is code behind file
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestWeb
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.BackColor = Color.Red;// It is not working.
}
}
}
This is web.config file
<?xml version="1.0"?>
<configuration>
<system.web>
<pages>
<namespaces>
<clear/>
<add namespace="System.Drawing" />
</namespaces>
</pages>
</system.web>
</configuration>
Edit
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestWeb._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
Label1.BackColor = Color.Red;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:label ID="Label1" runat="server" text="Label"></asp:label>
</div>
</form>
</body>
</html>
The <namespaces> element only applies to aspx pages.
Unlike VB.Net, C# has no mechanism to automatically include namespaces in ordinary code files.
You should try this and then try.
<configuration>
<system.web>
<pages>
<namespaces>
<clear/>
<add namespace="System.Drawing" />
<add namespace="System" />
</namespaces>
</pages>
</system.web>
</configuration>
The namespaces configuration section is for pages, not code behind. A code behind file express all namespace imports within itself. The namespaces included in configuration will be included in the dynamic class that is generated from your .aspx page.
As SLaks says, that will not work. If you're looking for a shortcut to always having a namespace included, consider editing the default VS templates, so that it's always there when you create a new one.

Categories