character encoding with asp.net dynamic textbox - asp.net

Environment: .net 3.5, c#, sharepoint 2010
Existing functionality: I have a user control with a search text box and search button. When the submit button is hit, along with search results, a querystring with search keyword is built. On postback, the textbox is again populated with the search keyword from querystring. This works good.
Issue: Need to fix cross side scripting. so did a html.encode and again a filter to escape single quote with &amp#39; for the textbox value. but the textbox displays value as it is like "'searchingstring'".
I need to show the user only "Searchstring", but the value in the sourcecode should be &amp#39;searchingstring&amp#39; to prevent cross side script vulnerability.
(Note: Above text "&amp" is actually "&". not &amp#39. Since stackoverflow editor transforms it to single quotes, i replaced it with &amp for reading)
If i tried building the textbox dynamically on pageinit using stringbuilder, I am getting what i needed as i mentioned above.
eg:
StringBuilder sb = new StringBuilder();
if (Request.QueryString["str"] != null)
{
string strName = Request.QueryString["str"].ToString();
str_value = htmlCheckReturnData(strName ); //encoded string
sb.Append("<INPUT type='TEXT' runat = 'server' id = 'mystring' value = '" + str_value + "' />");
// Response.Write(sb.ToString());
}
else
{
sb.Append("<INPUT type='TEXT' runat = 'server' id = 'mystring' value = '' />");
}
ltlSearch.Text = sb.ToString();
But I need to check the value of the "mystring" text box inside pageload like,
if (!IsPostBack && !Page.IsAsync)
{
if (!string.IsNullOrEmpty(mystring.Value)) //NOT WORKING HOW TO GET the textbox value
{
//do something
}
}
Note: If I create the textbox control on page_init without a stringbuilder write method, the character with encoding displays on the textbox.
Any help?
Thanks
Venkat

Appending a string in your html, with runat="server" does not make it a server control. You will have to add your control dynamically from code behind, in page_init like this:
Add a PlaceHolder control:
<asp:PlaceHolder runat="server" ID="myPlaceHolder">
</asp:PlaceHolder>
Then this code in your Page_Init event to create the TextBox control:
protected void Page_Init(object sender, EventArgs e)
{
TextBox txt = new TextBox();
txt.ID = "myTxt";
myPlaceHolder.Controls.Add(txt);
}
To get the Control from the Page_Load event:
TextBox txt = (TextBox)myPlaceHolder.FindControl("myTxt");
now you can access the Text property like you would with any other control:
txt.Text
Couple of things. Adding controls dynamically could be sometimes a painfully experience. Asp.net is not handling this control's viewstate right now. So you might receive some errors depending on what you are trying to accomplish. There are tons of tutorials online that will help you in this process.
Dynamically Create Controls in ASP.NET with Visual Basic .NET
TRULY UNDERSTANDING DYNAMIC CONTROLS (PART 1)
Add Controls to an ASP.NET Web Page Programmatically

Related

Dynamically adding Textbox in asp.net using C#

I have written a code in which a textbox is dynamically added to a gridview cell. There is some default texts in the textbox. I want that when users will click on the textbox the default text will disappear and the user can then write anything on it only in number, i.e. the user will not be able to use letters or special characters.
Kindly let me know how to achieve this.
Code example
Gridview gv=new Gridview();
gv.DataSource=dt;
gv.DataBind();
Textbox t1 = new Textbox();
t1.Text="Outages if any(in mins)";
gv.Rows[0].Cells[0].Controls.Add(t1);
Need help after this, something like when user puts his cursor in the textbox , the default text will disappear , and if the user removes the cursor without writing anything , the default text will reappear. Also the default text should be a bit blurred
Thanks.
Try something like this
Textbox t1 = new Textbox();
t1.Attributes.Add("onclick", "if(this.value == 'default text') this.value = '';"
t1.Attributes.Add("onblur", "if(this.value == '') this.value = 'default text';" />
You could also use onfocus in case users use tab key
With this, using this.value, approach you don't need to know the client ID of the control.
Here is a post describing exactly what you are looking to do:
HowTo: including default text in a Textbox while enforcing server-side validation
The pertinent points are:
Adding javascript attribute to onfocus & and onblur:
txtName.Attributes.Add("onfocus","clearText()");
txtName.Attributes.Add("onblur","resetText()");
Adding the javascript to clear and repopulate the textbox:
function clearText() {
document.form1.txtName.value = ""
}
function resetText() {
if(document.form1.txtName.value == "")
document.form1.txtName.value = "(enter something here)"
You can do this. The easiest way is to use the ajaxControlToolkit. You can create controls dynamically. For example:
Dim mt As new TextBox
Dim newTest As New AjaxControlToolkit.TextBoxWatermarkExtender
With mt
.ID = "textBox1"
.TextMode = TextBoxMode.SingleLine
End With
With newTest
.ID = "TextBoxWatermarkExtender1"
.TargetControlID = mt.ClientID
.WatermarkText = "test"
End With
Then just add both controls to the gridview as you are doing with the textbox. If you are not using Ajax, you can add javascript to the control through codebehind but this is more difficult. Let me know if that is what you want to do and Ill add some code to show you how.
This should create a textbox control with an associated ajax TextBoxWaterMarkExtender.

Access dynamically generated control from code behind

I load a piece of html which contains something like:
<em> < input type="text" value="Untitled" name="ViewTitle" id="ViewTitle" runat="server"> </em>
into my control. The html is user defined, do please do not ask me to add them statically on the aspx page.
On my page, I have a placeholder and I can use
LiteralControl target = new LiteralControl ();
// html string contains user-defined controls
target.text = htmlstring
to render it property. My problem is, since its a html piece, even if i know the input box's id, i cannot access it using FindControl("ViewTitle") (it will just return null) because its rendered as a text into a Literal control and all the input controls were not added to the container's control collections. I definitely can use Request.Form["ViewTitle"] to access its value, but how can I set its value?
Jupaol's method is the prefer way of adding dynamic control to a page.
If you want to insert string, you can use ParseControl.
However, it doesn't cause compilation for some controls such as PlaceHolder.
Your process is wrong, you are rendering a control to the client with the attribute: runat="server"
This attribute only works if the control was processed by the server, you are just rendering as is
Since your goal is to add a TextBox (correct me if I'm wrong), then why don't you just add a new TextBox to the form's controls collection???
Something like this:
protected void Page_Init(object sender, EventArgs e)
{
var textbox = new TextBox { ID="myTextBoxID", Text="Some initial value" };
this.myPlaceHolder.Controls.Add(textbox);
}
And to retrieve it:
var myDynamicTextBox = this.FindControl("myTextBoxID") as TextBox;
I have created several working examples and they are online on my GitHub site, feel free to browse the code

Postback From Controls inside Composite Web Control

Let's say we have a composite web control with a combobox and a textbox. Is it possible to build into the control functionality such that when the text in the textbox changes, it posts back and adds the value as an option in the combobox?
I know that I could add an "onchange" handler to the textbox and make something work with Javascript, but that's not really what I'm looking to do. Is there a way to just put like:
Protected Sub txt1_TextChanged(sender As Object, e As System.EventArgs) Handles txt1.TextChanged
combo1.items.add(txt1.Text)
End Sub
in the web control code and it connect to the TextChanged event of the textbox?
In short yes, you should be able to do this.
I don't know what syntax you need for VB, but I have done similar things multiple times in C#. For C# you would add the name of the even handler to the markup of your text box, and set auto postback on the text box to true. Then the code behind event handler does what ever work you need it to.
As a rule I also define a custom event on the web control, and have the event handler for the textbox raise this custome event as well. This gives the option of letting the page that is using the control act on the event as well.
EDIT:
Here is an example with a DropDownList, it was part of a control to look up users within a set of Active Directory domains. If the user changed what domain they had selected we wanted it to search for the previously entered values on the new domain.
Mark-up:
<asp:DropDownList ID="ddl_Domain" runat="server" onselectedindexchanged="ddl_Domain_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>
Code behind:
protected void ddl_Domain_SelectedIndexChanged(object sender, EventArgs e)
{
if (UserID != "" || LastName != "" || FirstName != "" || EmailAddress != "")
{
lnk_Find_Click(sender, e);
}
}
Or in the case where I have added a child control dynamically through code I have used this syntax:
DropDownList ddl = new DropDownList();
ddl.ID = "ddl";
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.SelectedIndexChanged += This_SelectedValue_Changed;
ddl.AutoPostBack = true;
As I said, I am not sure how to make this work with the Handles syntax of VB but it should be possible.

Adding custom valiadtion to ASP.NET controls

We're trying to build a simple asp control for some clients where they can just drop in a single block -
i.e.
<captcha:CaptchaControl ID="CaptchaControl1"
runat="server"
Server="http://localhost:51947/"
/>
and have it render the control. The catch is that I can't get this to include custom validation. Right now I'm using the RenderContents function to display the layout of the control itself as well as hook it up the to Javascript. The problem is that I don't know how to get custom validation to fire when used as part of a control.
protected override void RenderContents(HtmlTextWriter output)
{
output.Write(#"
<script type=""text/javascript"" src=""http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js""></script>
<link rel=""stylesheet"" type=""text/css"" href=""/Layout/CaptchaLayout.css"" />
//etc
<asp:Textbox id=""text1"" runat=""server"" text=""""></asp:Textbox>
<asp:CustomValidator id=""CustomValidator2"" runat=""server""
ControlToValidate = ""text1""
ErrorMessage = ""You must enter at least 8 characters!""
ClientValidationFunction=""validateLength"" >
</asp:CustomValidator>"
);
}
Any suggestions for a better way to do this?
Oogh, I would definitely not recommend your approach. It's very brittle and difficult to maintain, and depending on how your control is used, I'm not even sure that you can output more asp tags and have them processed properly.
Why don't you just inherit your custom control from Panel, and then in the Init or Load event handlers, add the textbox and custom validator to it? Roughly:
public class MyControl : Panel
{
public MyControl()
{
}
protected override void OnInit(EventArgs e)
{
ScriptManager.RegisterScript( ... Google script, CSS, etc. ... );
TextBox txt = new TextBox();
txt.ID = "text1";
this.Controls.Add(txt);
CustomValidator vld = new CustomValidator();
vld.ControlToValidatre = "text1";
vld.ID = "validator1";
this.Controls.Add(vld);
}
}
Your CustomValidator doesn't work because ASP.NET has no idea it's there. You are basically just dumping that output to the response... ASP.NET is not interpreting it.
It seems to me that this is a perfect situation for a User Control rather than a Custom Control. Just drop that output string in its own .ASCX file.

ASP.Net - repeating input boxes on the client side using Repeater

I have the following requirement for creating a user profile in my application:
User should be able to enter multiple phone numbers/email addresses in his profile.
The screen looks somewhat like this:
- By default, on page load a single textbox for phone and email are shown.
- User can click a "+" button to add additional numbers/addresses.
- On clicking the "+" button we need to add another textbox just below the first one. User can add as many numbers/addresses as he wants. On submit, the server should collect all numbers/emails and save it in DB.
I tried using the Repeater control to do this. On page_load I bind the repeater to a "new arraylist" object of size 1. So, this renders fine - user sees a single textbox with no value in it.
When he clicks the "+" button, I ideally want to use javascript to create more textboxes with similar mark-up as the first.
My questions are these:
Can I render the new textboxes anyway using js? I notice that the HTML rendered by the repeater control is somewhat complex (names/ids) etc. and it might not be possible to correctly create those controls on client-side.
If there is a way to do #1, will the server understand that these additional inputs are items in the repeater control? Say, I want to get all the phone numbers that the user entered by iterating over Repeater.DataItems.
Conceptually, is my approach correct or is it wrong to use the Repeater for this? Would you suggest any other approach that might handle this requirement?
Coming from a Struts/JSP background, I am still struggling to get a grip on the .NET way of doing things - so any help would be appreciated.
The repeater control may be a bit of overkill for what you're trying to accomplish. It is mainly meant as a databound control for presenting rows of data.
What you can do is to dynamically create the boxes as part of the Page_Load event (C#):
TestInput.aspx :
<form id="form1" runat="server">
<asp:HiddenField ID="hdnAddInput" runat="server" />
<asp:Button ID="btnPlus" OnClientClick="setAdd()" Text="Plus" runat="server" />
<asp:PlaceHolder ID="phInputs" runat="server" />
</form>
<script type="text/javascript">
function setAdd() {
var add = document.getElementById('<%=hdnAddInput.ClientID%>');
add.value = '1';
return true;
}
</script>
TestInput.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["inputs"] == null)
ViewState["inputs"] = 1;
if (hdnAddInput.Value == "1")
{
ViewState["inputs"] = int.Parse(ViewState["inputs"].ToString()) + 1;
hdnAddInput.Value = "";
}
for (int loop = 0; loop < int.Parse(ViewState["inputs"].ToString()); loop++)
phInputs.Controls.Add(new TextBox() { ID = "phone" + loop });
}
I ended up using a PlaceHolder to dynamically add the text boxes and a HiddenField to flag when another TextBox needed to be added. Since the IDs were matching, it maintains the ViewState of the controls during each postback.
Welcome to the hairball that is dynamically-added controls in ASP.NET. It's not pretty but it can be done.
You cannot add new fields dynamically using javascript because the new field would have no representation in the server-side controls collection of the page.
Given that the requirements are that there is no limit to the number of addresses a user can add to the page, your only option is to do "traditional" dynamic ASP.NET controls. This means that you must handle the adding of the control server-side by new-ing a new object to represent the control:
private ArrayList _dynamicControls = new ArrayList();
public void Page_Init()
{
foreach (string c in _dynamicControls)
{
TextBox txtDynamicBox = new TextBox();
txtDynamicBox.ID = c;
Controls.Add(txtDynamicBox);
}
}
public void AddNewTextBox()
{
TextBox txtNewBox = new TextBox();
txtNewBox.ID = [uniqueID] // Give the textbox a unique name
Controls.Add(txtNewBox);
_dynamicControls.Add([uniqueID]);
}
You can see here that the object that backs each dynamically-added field has to be added back to the Controls collection of the Page on each postback. If you don't do this, data POSTed back from the field has nowhere to go.
If you want to user the repeater, I think the easiest way is to put the repeater in a ASP.Net AJAX update panel, add the extra textbox on the sever side.
There are definitely other way to implement this without using repeater, and it maybe much easier to add the textbox using js.
No, but you can create input elements similar to what TextBox controls would render.
No. ASP.NET protects itself from phony data posted to the server. You can't make the server code think that it created a TextBox earlier by just adding data that it would return.
The approach is wrong. You are trying to go a middle way that doesn't work. You have to go all the way in either direction. Either you make a postback and add the TextBox on the server side, or you do it completely on the client side and use the Request.Form collection to receive the data on the server side.

Resources