Make multiline textbox remember text input (auto complete) - asp.net

A normal asp.net textbox will remember your old inputs - if you type something into a textbox and leave the page then come back, and type the same thing. The textbox will "auto complete" what you are typing by suggesting what you typed the last time.
I can see that if you set the Textmode property to "multiline" the textbox then loses it's auto complete. Like this:
<asp:TextBox ID="TextBox_Description" TextMode="MultiLine" MaxLength="500" runat="server"></asp:TextBox>
How do I add this funcitonality to my multiline asp Textbox or a TextArea? (multiline textboxes are rendered as textareas).
I am open to both asp.net specific solutions and javascript/jquery solutions.

You can retrieve what was in the multiline textbox and then cache it and on a postback use the cache to output what was used before.
// Get everything in the multiline text box and cache it
Cache["multilineValues"] = TextBox_Description.Text;
// Output what was written again through cache etc when the page loads after a postback.
//You would most likely put this in the Page_Load method.
if(IsPostBack)
{
if(Cache["multilineValues"] != null)
{
//Use what was written before
TextBox_Description.Text = (string)Cache["multilineValues"];
}
}

Related

character encoding with asp.net dynamic textbox

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

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

asp.net Button event inside jQuery FaceBox [duplicate]

This question already has answers here:
Facebox adding commas to input
(3 answers)
Closed 3 years ago.
I'm using jQuery FaceBox to show a textbox, a dropdownlist and a button. The user can write a text in the textbox, select a value in the ddl abd hit the button. This fires some code in the codebehind. The FaceBox shows fine, and the content in it is also ok. Also, the button event is fired. This is the code for the button event handler:
protected void Button1_Click(object sender, EventArgs e)
{
_favorit = new Favoritter();
ListItem fav = ddl_favoritter.SelectedItem;
_favorit.FavoritterFolderID = int.Parse(fav.Value);
//_favorit.FavoritterFolderID = Convert.ToInt32(ddl_favoritter.SelectedItem);
_favorit.FavoritterNavn = txt_favoritNavn.Text;
_favorit.FavoritterUserID = UserID;
_favorit.FavoritterUrl = HttpContext.Current.Request.Url.ToString();
FavoritterManager.InsertFavoritter(_favorit);
}
A business object is created, and its properties set with the values read from the controls. The object is then inserted into a database, which works just fine. The problem is that the textbox and dropdown values are not set properly. The textbox value is empty, and the ddl selected value is allways 1, even though I write in the textbox, and select another ddlitem before I hit the button. The ddl is loaded like this:
if (!Page.IsPostBack)
{
_favoritter = FavoritterFolderManager.GetFavoritterFolderByUser(UserID);
ddl_favoritter.DataSource = _favoritter;
ddl_favoritter.DataBind();
}
I tried putting this code outside if (!Page.IsPostBack), and also filling it using an objectdatasource, still the same issue. It's like the controls are "reset" as I hit the button, and I don't think it has anything to do with the FaceBox, as all it does is to show the div that contains the controls... Then again, it might... Any ideas?
This is the code in the aspx page:
<div id="showme" style="display:none;">
Add to favourites.<br />
<br />
<p>
Title: <span><asp:TextBox ID="txt_favoritNavn" runat="server"></asp:TextBox></span></p>
<p>
select folder: <span><asp:DropDownList ID="ddl_favoritter" runat="server" DataTextField="FavoritterFolderNavn"
DataValueField="FavoritterFolderID" AppendDataBoundItems="true">
</asp:DropDownList>
</span>
</p>
<br />
<asp:Button ID="Button1" runat="server" Text="Gem" onclick="Button1_Click"/>
</div>
You need to have the code that fills the text box and selects the drop down item inside of the if(!IsPostBack) block, because the page load event fires again before the button event (See the ASP.NET Page Life Cycle for more info on this). Have you tried enabling view state on the control? That may be part of the issue.
Change
$('body').append($.facebox.settings.faceboxHtml)
to
$('form').append($.facebox.settings.faceboxHtml)
The problem is a lot of these controls, not just FaceBox append themselves to the body by default. jQuery UI dialog does this as well.
See this question for a fix: JQuery Facebox Plugin : Get it inside the form tag
When things happen outside the <form> tag, they're disconnected from how ASP.Net works. When you clicked submit, the values from those inputs weren't inside the form, so didn't submit to the server...which is why you aren't seeing the values.
This is the quick answer from that question, credit to Kevin Sheffield:
poking around the facebox.js I came across this line in the function init(settings)...
$('body').append($.facebox.settings.faceboxHtml)
I changed that to ...
$('#aspnetForm').append($.facebox.settings.faceboxHtml)

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.

Odd issue with textbox and ASP.NET

This code was working properly before, basically I have a master page that has a single text box for searching, I named it searchBox. I have a method to pull the content of searchBox on form submit and set it to a variable userQuery. Here is the method:
Public Function searchString(ByVal oTextBoxName As String) As String
If Master IsNot Nothing Then
Dim txtBoxSrc As New TextBox
txtBoxSrc = CType(Master.FindControl(oTextBoxName), TextBox)
If txtBoxSrc IsNot Nothing Then
Return txtBoxSrc.Text
End If
End If
Return Nothing
End Function
The results are displayed on search.aspx. Now, however, if searchBox is filled and submitted on a page other than search.aspx, the contents of the text box are not passed through. The form is very simple, just:
<asp:TextBox ID="searchBox" runat="server"></asp:TextBox>
<asp:Button ID="searchbutton" runat="server" Text="search" UseSubmitBehavior="True" PostBackUrl="~/search.aspx" CssClass="searchBtn" />.
I think because you are using PostBackUrl, you are going to be required to use the "PreviousPage" identifier to reference your variable.
Another solution would to not use the PostBackUrl property and to capture the event within the user control (I'm assuming you are encapsulating this in one location) and then use the:
Response.Redirect("/search.aspx?sQuery=" & Server.URLEncode(searchBox.Text))
since you are not necessarily passing sensitive data, this should be acceptable as well.
I agree with Kyle as to why it doesn't work and the solution if you want to continue to access the value via the text control, but you can also pluck the form data out of the httprequest. I think like this (my asp.net is a bit rusty)
Request.Form[txtBoxSrc.UniqueID]
This plus other techniques (using the previouspage property) are documented here: http://msdn.microsoft.com/en-us/library/6c3yckfw(VS.80).aspx. It seems all you need to do is:
if (Page.PreviousPage != null)
{
TextBox SourceTextBox =
(TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null)
{
return SourceTextBox.Text;
}
}
Updated: Thanks to Jason Kealey for pointing out I needed to use UniqueID.

Resources