Auto-complete method does not get called - asp.net

I'm not sure what is wrong, this is my first time spinning this up. Looking at the ajax examples, all should be working.. but my method does not get called.
I am not making use of a webservice, and want to return my suggestions from a page method.
<asp:TextBox ID="searchBox" runat="server" CssClass="searchTextBox"></asp:TextBox>
<asp:AutoCompleteExtender ID="searchBox_AutoCompleteExtender" runat="server"
DelimiterCharacters="" Enabled="True" ServiceMethod="_get_Suggestions"
TargetControlID="searchBox">
</asp:AutoCompleteExtender>
Page Method:
Private Function _get_Suggestions(prefixText As String, count As Int16) As String()
Dim array() As String = {"doggy", "catty", "fishy"}
Return array
End Function
Also tried:
<WebMethod()> <Script.Services.ScriptMethod()> Public Shared Function _get_Suggestions(prefixText As String, count As Int16) As String()

My Extender AND method, was on my masterpage. After some hints on similar issues, it seems I cant have my page method on the masterpage code behind.
I have to put the page method, in my content page, while the extender itself, can be in my masterpage.
Why? No clue... Maybe someone can elaborate to improve this answer.

Related

asp:textbox calling asp:button handler on text change

I have the most bizarre problem happening ... I'm controlling a menu edit page and I have a series of controls, an asp:textbox with the numeric ID of the menu being worked on, flanked by - and + buttons to decrement and increment the ID. The user can type a new index in the textbox, or use the buttons. Easy peasy, right?
Here's the ASPX markup:
<asp:Button id="menuDown" runat="server" CausesValidation="false" OnClick="DownClick" Text="-" />
Menu # <asp:textbox runat="server" MaxLength="5" Columns="3" id="tbMenuId" />
<asp:Button id="menuUp" runat="server" CausesValidation="false" OnClick="UpClick" Text="+" />
There's a CompareValidator further down the page ensuring a non-negative, numeric entry.
Over in my code behind, my Page_Load pulls the value out of the textbox without problems:
Try
menuId = Integer.Parse(tbMenuId.Text)
Catch
menuId = 0
tbMenuId.Text = "0"
End Try
This works great (with ONE caveat) — every time I change the menu ID via the textbox, after the Page_Load method pulls the new value out of the text box perfectly, the DownClick handler gets called, decrementing the desired ID.
So far, the ONLY way I've managed to have the requested menu appear is to eliminate the two asp:Button controls. Eliminating only the menuDown button causes the UpClick handler to get called.
I had an OnTextChanged="..." attribute on the asp:Textbox control, but that handler NEVER got called and didn't seem necessary anyway, so I pulled it.
I cannot help but think the two behaviors must be connected.
Anyone understand WHY this is happening?
This qualifies as hacky work-around, rather than a fix, but it does let me proceed forward until this behavior can be explained.
The OnTextChanged event is firing the way it's supposed to now (not sure what I did wrong the first time) so, I used it to implement the hackiest of hacks ...
Protected Property hackyFlag As Boolean ' Suppress button click (true) after text change
' ... value in session variable
Protected Sub tbMenuId_TextChanged(sender As Object, e As EventArgs)
Integer.TryParse(tbMenuId.Text, menuId)
hackyFlag = True
End Sub
Protected Sub DownClick(sender As Object, e As EventArgs)
If hackyFlag Then : hackyFlag = False : Return : End If
If menuId > 0 Then menuId -= 1
tbMenuId.Text = menuId
End Sub
Gross, hacky, and disgusting ... but it works. :-) The button handler is still being called incorrectly, but now it's smart enough to do what I want instead of what the framework is telling it to do.
Still open to better answers and/or explanations as to why this is happening on this page and hasn't happened on any other. ( knock on wood )

Server Side Custom Validator Not Firing

I'm having an odd problem in that one of the 4 custom validators on my web page is not firing. Everything looks correct based on the working validators. Below is the simplified code.
ASPX code -
<asp:TextBox ID="CMT_TXT" runat="server" Columns="60" Rows="8"
TextMode="MultiLine" Text='<%#Eval("CMT_TXT")%>'></asp:TextBox><br />
<asp:CustomValidator ID="csvCMT_TXT" runat="server" ControlToValidate="CMT_TXT"
Display="Dynamic" EnableClientScript="False" ErrorMessage="Msg">
</asp:CustomValidator>
VB code -
Public Sub csvCMT_TXT_ServerValidate(source As Object,
args As ServerValidateEventArgs) _
Handles csvCMT_TXT.ServerValidate
dim s As String = CMT_TXT.Text
args.IsValid = s.Length <= 3500
End Sub
When testing,
The contents of field CMT_TXT has approximately 3000 characters. So it is not an empty field issue.
Page.Validate is called in the main body of the code
for server side validation to fire you need to call Page.Validate, this should trigger all your server side validation and update Page.IsValid
Also it does not look like you have the event set up on the custom val. may want to add the prop OnServerValidate
OnServerValidate="csvCMT_TXT_ServerValidate"
<asp:CustomValidator ID="csvCMT_TXT" runat="server" ControlToValidate="CMT_TXT"
Display="Dynamic" EnableClientScript="False" ErrorMessage="Msg" OnServerValidate="csvCMT_TXT_ServerValidate">
</asp:CustomValidator>
I'm not too familiar with VB.NET, but with C# I'll check the Page.IsValid field before continuing on with a page that has a CustomValidator.
An example with a Wizard control that contains a CustomValidator in the final stage, I will check this value in the FinishButtonClick event.
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
if (Page.IsValid == false)
{
// validator failed, stop wizard from continuing
return;
}
// page is valid, continue on
// ...
}
Not sure if there are any differences with VB.NET, but may be worth a shot
At a glance, it looks like you named your handler incorrectly. The control ID is csvCMT_TXT while the handler is csv_CMT_TXT.ServerValidate. There's an extra _ in the handler.
The problem turned out to be a problem with the VS2010 project build.
To this the problem, I had to
Deleted all files in BIN directory
Deleted all file in OBJ directory
Deleted Custom Validator
Rebuilt the Project
Add Custom Validation back into program. Added the original code back into program
It's a bit extreme, but this is what it took to resolve the problem.

using ClientScriptIncludeRegister to get a hidden field value

I am implementing a web application using ASP.NET/VB. The front-end (.aspx) executes an external .js file as:
<script type =" text/javascript" src="External.js"></script>
where it contains some functions. One of these functions called populateHidden() is used to assign a value to the hiddenField I defined on the front-end (.aspx) as follows:
In External.js
document.getElementByID('Hidden2').value = "dsadsadas";
In .aspx
<input id="Hidden2" type ="hidden" runat="server" />
what I have been trying to do is to get the value assigned to Hidden2 and pass it to the server-side (.aspx.vb) using:
Dim str = Hidden2.value
However, since server-side code executes first,str would be empty and unless a postback is done somehow whether using a Button or a Timer to reload the front-end, then str will have dsadsadas. I do not intend to reload the page or initialize a postback. I tried window.onload = populateHidden() with no luck. This situation made me desperate since I tried to many things making sure I do not use postbacks or reloads until I came across ClientScriptManager.RegisterClientScriptInclude Method . I couldn't not get around onto how I can use such an example to solve my situation.
The idea in mind is to call or execute External.js from the server side (since it executes first), then populate Hidden2 on the front-end, go back to the server side and retrieve Hidden2.value.
However the example in the link mentioned earlier, the server-side code is written in the front-end but I want to write it on the server-side (.aspx.vb).
The reason why I need Hidden2.value in the server-side is to store it in my sql_database. Any suggestions, advice or solutions to get Hidden2.value from the front-end would be really appreciated.
The following solution uses only ASP.Net Ajax Engine. In PageLoad event, a call to populateHidden() function is being registered. In the codebehind, a method marked with the WebMethod attribute was added, allowing it to be called by an Ajax request (without postback). So, when the button is clicked, the javascript function sendHiddenValueToServer() is called, making an Ajax request to the Page Method, passing the Hidden Field Value as Parameter.
First, you will need a ScriptManager declared with the EnablePageMethods property set to true:
<asp:ScriptManager runat="server" EnablePageMethods="true" />
I tested using the following markup:
<html>
<head runat="server">
<title></title>
<script src="External.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" EnablePageMethods="true" />
<div>
<asp:HiddenField ID="Hidden2" runat="server" ClientIDMode="Static" />
<button id="button1" onclick="sendHiddenValueToServer();">
Send Value to Server</button>
</div>
</form>
</body>
</html>
In the Javascript file:
function populateHidden() {
document.getElementById('Hidden2').value = "dsadsadas";
}
function sendHiddenValueToServer() {
PageMethods.ReceiveHiddenValue(
document.getElementById('Hidden2').value,
function () { alert("success!") },
function () { alert("error!") });
}
And in the codebehind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "register", "populateHidden();", True)
End If
End Sub
<System.Web.Services.WebMethod()>
Public Shared Sub ReceiveHiddenValue(ByVal value As String)
Dim str As String = value
' Save Value to database
End Sub

AjaxControlToolkit AutoCompleteExtender ... how to fill from linq query?

Go easy... I'm a newbie at this.
Ok, I've added the AutoCompleteExtender to my webpage. The user will add search tags to a project, and I want the textbox to autocomplete with tags that already exist in the database.
I don't have a "registry" for tags; only a table with a tagName and a projectID. So, a tagName might be repeated many times in the table. So I just want to return distinct results in my query. (That's easy.)
But how do I tie it to the AutoCompleteExtender? I'm not well versed in WebServices, etc...
I'm using entity framework, fyi...
Here's my autocomplete code on the aspx page:
<asp:TextBox ID="TagNameTextBox" runat="server"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="TagNameTextBox_AutoCompleteExtender"
runat="server"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="2"
EnableCaching="false"
DelimiterCharacters=""
Enabled="True"
TargetControlID="TagNameTextBox">
</ajaxToolkit:AutoCompleteExtender>
And here's my linq query:
var qrygettags = (from t in db.TagTables
select new { t.TagName }).Distinct().ToString();
I found a few examples of a jquery solution, too, but I don't know how to get my query into that format. Any help or ideas would be greatly appreciated!
Well, I kept hunting around and found this seemingly easy solution, and it works for me.
in the aspx page, in the control, I have
ServiceMethod="GetTagNames"
and in the cs page I added this in the page load:
[System.Web.Services.WebMethod]
public static string[] GetTagNames(string prefixText, int count)
{
mydatabase db = new mydatabase();
return db.TagTables.Where(n => n.TagName.StartsWith(prefixText)).OrderBy(n => n.TagName).Select(n => n.TagName).Distinct().Take(count).ToArray();
}
Hopefully it will help someone else out there!

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