First letter disappears on Ajax Toolkit AutoCompleteExtender - asp.net

My CompletionInterval is 100 and MinimumPrefixLength is 1. Sometimes after typing one letter that I know has completions, like 'a', after roughly one second, maybe less (but 1 second is a specified time), that initial 'a' disappears. When I type another one, I get a list of completions? Does anyone know what is going on here? I'm using v7.0607 of the AjaxControlToolkit that brings v1.4.6 of the HtmlAgilityPack with it.
My AutoCompleteExtender and associates look like this:
<asp:HiddenField runat="server" ClientIDMode="Static" ID="autoCompleteHidden" OnValueChanged="autoCompleteHidden_ValueChanged" />
<asp:TextBox ID="txtSearchField" runat="server" Width="200px"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtSearchField"
ServicePath="~/AutoComplete.asmx" ServiceMethod="GetVisitors" Enabled="False" CompletionInterval="100"
MinimumPrefixLength="1" CompletionSetCount="30" OnClientItemSelected="OnAutoCompleteSelected"
CompletionListCssClass="CompletionList" CompletionListItemCssClass="CompletionListItem"
CompletionListHighlightedItemCssClass="CompletionListHighlightedItem">
</ajaxToolkit:AutoCompleteExtender>
NOTE: Enabled is set to True before this control group is used and back to False afterwards. That is NOT the problem.
The accompanying function script, below, works fine.
<script type="text/javascript">
function OnAutoCompleteSelected(source, eventArgs) {
$("#autoCompleteHidden").val(eventArgs._text);
__doPostBack("autoCompleteHidden", "");
}
</script>
That script triggers the following code-behind handler that fetches the details for the selected visitor. It also works fine:
protected void autoCompleteHidden_ValueChanged(object sender, EventArgs e)
{
var myVisitorObj = new XTime.OL.VisitorObj();
myVisitorObj = XTime.BL.myVisitor.SelectVisitorByFullName(autoCompleteHidden.Value);
if (myVisitorObj.MST_SQ != 0)
{
XTime.XTimeVariables.VisitorObj = myVisitorObj;
}
ddlSearchBy.SelectedIndex = 0;
AutoCompleteExtender1.Enabled = false;
//Need to reload page for Sessions variable to change
Response.Redirect(Request.Url.ToString());
}

Related

how to store a label control text into a textbox control value

i am trying to set the value of a textbox control in my aspx page as the value of a label text. I am using the following code but nothing happens. I have tried from the code behind file using c# and then I want to assign the textbox value to a session variable. If I just assign a string value like "Hello"it works, but otherwise nothing works.
protected void btnBook_Click(object sender, EventArgs e)
{
txtmtcid.Text = blbtest.Text;
Session["mtcid"] = txtmtcid.Text;
//Response.Redirect("booknow.aspx");
}
}
I also tried with Javascript, but no use:
var mtcid = parsedData.employeeCode;
document.getElementById('txtmtcid').value = mtcid;
The above js code works fine if I am assigning the value of mtcid to a label text, but not for the text box. please help.
You don't show things that could be messing this up.
and we can't see your markup used.
What does your page load event look like. Keep in mind that EVERY button click, post-back or ANY control on the page with a event code stub WILL RUN the page load event EVERY time. the page load event runs every time, and BEFORE your button click code runs.
So, if I have this markup:
<asp:Label ID="blbtest" runat="server" Text="zoo"></asp:Label>
<br />
<asp:TextBox ID="txtmtcid" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
<br />
And then code behind of this:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
txtmtcid.Text = blbtest.Text;
}
I then get this when I click on the button
So, we can see how the lable text is now copy to the text box.
You have to post more markup, and give futher detilas (such as some grid view, repeater or any other boatload of features that well explain your issue).
Note that you can double click on the button in the web forms designer to create a event click for the button. Its possible that no event code for the button exists, and your button click code and code behind never runs.
So this is the markup:
<asp:Label ID="blbtest" runat="server" ClientIDMode="Static">
</asp:Label>
<asp:Button ID="btnBook" runat="server" Text="Book Now"
CssClass="spaces-info__button" OnClick="btnBook_Click"/>
<asp:TextBox ID="txtmtcid" runat="server">
</asp:TextBox>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!(Session["username"] == null))
{
string usn = Session["username"].ToString();
lblusn.Text = usn;
}
}
protected void btnBook_Click(object sender, EventArgs e)
{
txtmtcid.Text = blbtest.Text;
Session["mtcid"] = txtmtcid.Text;
Response.Redirect("booknow.aspx");
}
updated js:
$(function () {
//dom is ready
var request = new XMLHttpRequest;
var usn = document.getElementById('lblusn').innerHTML;
//var usn = "juhaina.ahmed";
console.log(usn);
request.open('GET', "URL" + usn + ""); //of course I have replaced
the URL here
request.onload = function () {
var response = request.response;
var parsedData = JSON.parse(response);
console.log(parsedData);
var nm = parsedData.fullName;
document.getElementById('lblfullnm').innerHTML = nm;
var mtcid = parsedData.employeeCode;
document.getElementById('blbtest').innerHTML = mtcid;
document.getElementById('txtmtcid').value =
document.getElementById('blbtest').innerHTML
};
request.send();
});
I am new to js, and asp.net, so trying to browse whatever possible and work things out here. The session variable value is just not getting passed to next page. Honestly, i dont need the textbox, I dont know if label text can be stored in session variables. If thats possible, then all I want to do is assign the blbtest label text to the session variable, but that also didnt work,but if I am hard coding it like:
Session["mtcid"]="D-11234"
this works and the value of session variable is passed.
hence I am trying now with textbox. Please let me know if theres a better approach to this.
If there is a way to avoid the use of the label and textbox and simply pass the session variable, Session["username"] from the code behind to the javascript, that would be great. how can I do it?

Set ContextKey for AutoCompleteExtender inside GridView

I have an AJAX AutoCompleteExtender, in a GridView, as seen below:
<asp:GridView
ID="GV1"
runat="server"
AllowPaging="True"
OnPageIndexChanging="GV1_OnPageIndexChanging"
OnRowCommand="GV1_RowCommand">
...
<asp:TextBox
ID="txt1"
runat="server"
onkeyup = "SetContextKey()">
</asp:TextBox>
<cc1:AutoCompleteExtender
ID="AutoCompleteExtender1"
runat="server"
TargetControlID="txt1"
ServiceMethod="GetACEList"
ServicePath="AutoComplete.asmx"
UseContextKey = "true"
MinimumPrefixLength="1"
EnableCaching="true"
CompletionSetCount="1"
CompletionInterval="100"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem">
</cc1:AutoCompleteExtender>
...
</asp:GridView>
When trying to set the context key, I am unable to access the AutoCompleteExtender on the client side as well as the server side.
On the client-side, I tried:
function SetContextKey() {
$find('AutoCompleteExtender1').set_contextKey($get("<%=ddlCountry.ClientID%>").value);
}
but JavaScript is unable to find the 'AutoCompleteExtender1' object. I realize that this is because there are a lot of 'AutoCompleteExtender1' objects in the generated HTML, each with a unique ID.
I then found this article, and I tried setting the context key on the server side:
protected void ddlCountry_OnSelectedIndexChanged(object sender, EventArgs e) {
AutoCompleteExtender1.ContextKey = ddlCountry.SelectedValue;
}
but the code compilation fails with the error:
The name 'AutoCompleteExtender1' does not exist in the current context
QUESTION:
How do I access the AutoCompleteExtender1 object on selected-index change of the drop down so I can set the context key?
Got it! I fixed how I was accessing the object incorrectly on the server side, and it worked!
Here's the server side code -- on selected-index change of the drop down, I loop through each of the rows of the GridView, and set each AutoCompleteExtender object's ContextKey to the drop-down's selected value:
protected void ddlCountry_OnSelectedIndexChanged(object sender, EventArgs e) {
foreach (GridViewRow gvRow in gvGV1.Rows) {
AjaxControlToolkit.AutoCompleteExtender AutoCompleteExtender1
= (AjaxControlToolkit.AutoCompleteExtender)gvRow.FindControl("AutoCompleteExtender1");
AutoCompleteExtender1.ContextKey = ddlCountry.SelectedValue;
}
}
Hope this helps someone stumbling upon this problem!
P.S:
I gave up trying to achieve the same thing on the client-side. I believe being able to set the Context Key on the server side (in C#) has a lot of advantages in terms of flexibility (like being able to change the context key as and when required, and not just on change of a drop-down). Still, if anyone knows how it can be done on the client-side (in JavaScript), please share.
Below code can be used if you want it to set at HTML end instead of c# code
for (var i = 0; i < grid.rows.length - 1; i++) {
var txtAmountReceive = $("input[id*=txt1]")
var GridRowID = (txtAmountReceive[i].valueOf('id').id).replace("txt1", "");
var AutoCompleteExt = GridRowID + 'AutoCompleteExtender1';
$find(AutoCompleteExt).set_contextKey("1");
}

ASPxGridview get row data from server-side

I'm working on a DevExpress Gridview and I want to get the data of the selected row (only one row can be selected at the time). I'm working on the Server-Side and I'm using FocusedRowChanged function.
EDIT: The FocusedRowChanged fire but nothing happen and the textboxes do not change value
protected void dxgrDepartement_FocusedRowChanged(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(GetType(), "FetchData", "<script language='javascript'>FetchData('4654654646')</script>");
txtDescription.Text = "patate";
//txtComments.Text = dxgrDepartement.GetRowValues(dxgrDepartement.FocusedRowIndex, "IdDepartment").ToString();
}
And the "FetchData :
function FetchData(text) {
//ClearField();
document.getElementById("<%= txtDescription.ClientID %>").value = text.toString();
}
BTW - Changing the callbacks property made no difference for us. We needed callbacks for other functionality so couldn't turn this off anyway.
The GetRowValues method did not work either.
This is a technique described on DevExpress' web site and it worked for us as long as we didnt use DevExpress' controls (ASPxDateEdit, ASPxTextBox):
ASPX page:
<dxwgv:GridViewDataTextColumn Caption="Dist. %" FieldName="DistributionPerc" VisibleIndex="3"
Width="50px">
<DataItemTemplate>
<asp:TextBox ID="txtDistPerc" runat="server" Text='<%# Eval("DistributionPercent") %>'
Width="50px" />
</DataItemTemplate>
</dxwgv:GridViewDataTextColumn>
Code behind:
for (int i = 0; i < grdHistory.VisibleRowCount; i++)
{
TextBox textbox = grdHistory.FindRowCellTemplateControl(i, grdHistory.Columns["DistributionPerc"] as GridViewDataColumn, "txtDistPerc") as TextBox;
var anything = textbox.Text;
}
Use:
gridView.GetRowValues(gridView.FocusedRowIndex, columnFieldName1, columnFieldName2, ..., columnFieldNameN)
Method ASPxGridView.GetRowValues
Property ASPxGridView.FocusedRowIndex
grid.EnableCallback = false; solved my problems!

How to hide a query string parameter in the url

I've a panel bar with some items in it. When I right click on the items and if I select "open in new tab", I need to open the link in a new tab.
For eg. if my page is "http:localhost/MyPage"
My grid is:
Name
abc
bcd
cde
When I click on the second item, the navigateUrl would be "http:localhost/MyPage/?Name=bcd"
This works fine.
But I want to hide the name in the url. Is there any other way, I can pass the name to next page without exposing it in the url. I could use sessions, but unfortunately, I cannot write it as a code for the default context menu.
You can use LinkButton objects. They will postback and then you can redirect requests to desired pages.
ASPX:
<asp:linkbutton id="lnkabcd" runat="server" text="abcd" onclick="lnkabcd_clicked"/>
C#:
public void linkabcd_clicked(object sender, EventArgs e)
{
Response.Redirect("URL OF TARGET PAGE");
}
Ofcourse it will be very cumbersome if you have lot of links. You can use grid (hope you are using it as you write in your question) and catch row event with command name and command argument properties.
To hide the url in addressbar of the browser, you need to do URL rewriting. For more on URL rewriting please visit these pages on codeproject and msdn.
You could set a cookie - that way the next time the user returns you could even return them to the same page (if you wanted to).
You may find this article helpful when deciding if this is a good option for you.
If you need to set the cookie on the client-side, then this article should help you out.
As #TheVillageIdiot said, url rewriting is a better approach. But you can use cross-page posting ability as well. Check it out:
Markup
<asp:HiddenField ID="HiddenField1" runat="server" ClientIDMode="Static" />
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="~/Second.aspx" Text='<%# Bind("Text") %>' OnClientClick='<%# "LinkButton1_Click(\"" + Eval("Value") + "\")" %>' />
</ItemTemplate>
</asp:Repeater>
<script type="text/javascript">
function LinkButton1_Click(v) {
document.getElementById('HiddenField1').value = v;
}
</script>
As you can see in the preceding code snippet, you have to add a hidden field to store the selected item by a simple javascript. Also I defined a property, called SelectedValue to get the value of the hidden field on the otherside.
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
Repeater1.DataSource = new[] {
new { Text = "Item 1", Value = "Item 1" },
new { Text = "Item 2", Value = "Item 2" },
new { Text = "Item 3", Value = "Item 3" }
};
Repeater1.DataBind();
}
public string SelectedValue
{
get { return HiddenField1.Value; }
}
Second Page
Add following directive to the destination page.
<%# PreviousPageType VirtualPath="~/Default.aspx" %>
Finally, you have access to the previous page via PreviousPage property of Page class.
string value = ((_Default)this.PreviousPage).SelectedValue;

Converting client side html radio buttons to asp.net web controls with dynamic ids. (ASP.net)(VB)

I have the following client side code in .aspx page within a datalist itemtemplate that takes questions from the database like this:
<Itemtemplate>
<b> <%=GetQuestionNum()%>)
<%#Server.HtmlEncode(Eval("Text").ToString())%></b>
<br />
<asp:Panel ID="A" runat="server" Visible='<%#GetVisible(Eval("OptionA").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="A">
<%#Server.HtmlEncode(Eval("OptionA").ToString())%>
</option><br />
</asp:Panel>
<asp:Panel ID="B" runat="server" Visible='<%#GetVisible(Eval("OptionB").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="B">
<%#Server.HtmlEncode(Eval("OptionB").ToString())%>
</option><br />
</asp:Panel>
<asp:Panel ID="C" runat="server" Visible='<%#GetVisible(Eval("OptionC").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="C">
<%#Server.HtmlEncode(Eval("OptionC").ToString())%>
</option><br />
</asp:Panel>
<asp:Panel ID="D" runat="server" Visible='<%#GetVisible(Eval("OptionD").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="D">
<%#Server.HtmlEncode(Eval("OptionD").ToString())%>
</option><br />
</asp:Panel></itemtemplate>
The output is like:
1) What is your age group?
- Option 1
- Option 2
- Option 3
- Option 4
The ID's of the radio buttons are dynamic ("Q" & QuestionID). If there is no answer to a question then the GetVisible function returns false and the containing panel is hidden.
I have been trying to get rid of the html and replace these with asp:radiobuttons but it is not possible to set id's from databinding.. only simply. I was trying something like:
<asp:RadioButton ID="Q<%#Eval("ID")%>" runat="server" Visible='<%#GetVisible(Eval("OptionA").Tostring())%>'
Text='<%#Server.HtmlEncode(Eval("OptionA").ToString())%>' />
Here is the function that provides data:
Public Shared Function GetQuestionsForSurvey(ByVal id As Integer) As DataSet
Dim dsQuestions As DataSet = New DataSet()
Try
Using mConnection As New SqlConnection(Config.ConnectionString)
Dim mCommand As SqlCommand = New SqlCommand("sprocQuestionSelectList", mConnection)
mCommand.CommandType = CommandType.StoredProcedure
Dim myDataAdapter As SqlDataAdapter = New SqlDataAdapter()
myDataAdapter.SelectCommand = mCommand
mCommand.CommandType = CommandType.StoredProcedure
mCommand.Parameters.AddWithValue("#id", id)
myDataAdapter.Fill(dsQuestions)
mConnection.Close()
Return dsQuestions
End Using
Catch ex As Exception
Throw
End Try
End Function
but I'm finding it impossible to work with the html controls, i.e get their .text value from codebehind, or adding events!
Please can an expert suggest a better way to replace the html with suitable asp.net web controls or from the codebehind and output it. Or point me in the right direction?
Thanks :0)
I had some experience with ASP controls and data binding. The problem you are facing is probably the fact that once you declare a control via markup you can't access it from data binding. Also, you should not confuse the server-side ID with the client-side ID.
The server-side ID, mapped to Id property of controls, is used to programmatically access the control from code behind. Client-side ID is the ID that will be placed in tag's id attribute and is mapped to ClientId property.
Judging from your question, what you need is to build a multi-choice survey, and, in my opinion, it's not important how the IDs are generated, just that they are properly grouped for each question.
I'll answer the part of programmatically accessing controls in data binding, which is a part of your question.
Here is an example from my code. Suppose you have a very simple GridView like this
<asp:GridView ID="example" runat="server" OnRowDataBound="DataBound">
<Columns>
<asp:TemplateField HeaderText="New">
<ItemTemplate>
<asp:Image ID="imgExample" runat="server" />
</ItemTemplate>
</Columns>
</asp:GridView>
It takes a data set during data binding and sets the image according to some property. It works the same as DataList, don't worry.
Now, in code behind, you handle the RowDataBoundEvent. You can't access the imgExample object directly, because it's a child of the ItemTemplate. When the row is bound, you have direct access to the row and then you can use the FindControl method of Control class
Here is C# code example (easy to convert to VB)
protected void DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) //Required
{
GridViewRow row = e.Row;
[...] //get an email message
(row.Cells[0].FindControl("imgExample") as Image).ImageUrl = (email.AlreadyRead)
? "Mail_Small.png"
: "Mail_New_Small.png";
}
}
Application to your case
In order to build a multi-choice survey, my advice is to create a DataList that will hold questions (the outer control) and then, for each row, declare a RadioButtonList that holds answers (the inner control). Bind the outer data list to the data set of questions and answers. Handle the RowDataBound event or whatever it's called in the DataList world. When you handle that event, bind the inner radiobuttonlist to the answers.
It should work for you
I am actually working on something similar at the moment. I am using javascript and jQuery to dynamically add controls to my page. After adding them to my page I have to get the new controls, their text, etc. The way I've been doing it is something like this:
<table id='BuilderTable' class="BuilderTable">
<tbody class='BuilderBody'>
</tbody>
</table>
<asp:Button runat="server" ID="saveButton" OnClick="SaveButton_Click" OnClientClick="SaveData()"
Text="Save Form" />
<asp:HiddenField runat="server" ID="controlsData" />
This table is where I put all my new controls.
Then when the client clicks the save button it first calls this javascript / jQuery function:
function SaveData() {
var controlRows = $('#BuilderTable tr.control');
var controls= [];
controlRows.each(function (index) {
//process control information here ...
controlText = //use jQuery to get text, etc...
var control = {
Index: (index + 1),
Text: controlText
};
controls.push(control);
});
var str = JSON.stringify(questions);
$('#<%= controlsData.ClientID %>').val(str);
}
Then the server side function for the button click is called (this in in C#, adapt to VB).
protected void SaveButton_Click(object sender, EventArgs e)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
string str = controlsData.Value;
List<Control> controls = jss.Deserialize<List<Control>>(str);
}
Using a Control class like this:
public class Control
{
public int Index { get; set; }
public string Text { get; set; }
}
This code uses javascript and jQuery to get your controls, JSON to serialize the data and save it in a asp hiddenfield then grab the data server-side and deserialize into objects that your code can use. Then take the data and do whatever you need to.

Resources