ASP.NET AJax Toolkit AutoCompleteExtender Issue - c#

Trying to implement the AutoCompleteExtender and coming up with a deadend Internal Server Error 500.
Page Method:
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> getcompletionlist(string prefix, int count)
{
string[] dccfields = null;
List<string> ret = new List<string>();
try
{
dccfields = DCC.get_field_names();
return OFControls.get_autocomplete_list(dccfields, prefix);
}
catch (Exception ex)
{
ret.Add("!" + ex.Message);
return ret;
}
}
aspx page:
<asp:TextBox ID="TextBox12" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender
ServiceMethod="getcompletionlist"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="false"
CompletionSetCount="1"
TargetControlID="TextBox12"
ID="AutoCompleteExtender1"
runat="server"
FirstRowSelected="false"
UseContextKey="True">
</asp:AutoCompleteExtender>
Coming up with error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error) [http://localhost:52966/QBIntegration.aspx]
I've tried adding Service Path - No change. Also specified another method name and got the 404 not found error so it seems that the code is being found just will not run. I also know that it is trying to load it because the 500 error comes up only when typing code in the textbox.
Also ... I do have the toolkitsriptmanager in the master page.
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" EnablePageMethods="true"></asp:ToolkitScriptManager>
Thanks in advance

The last few (if not more) of the AjaxToolKit does NOT require the AjaxScriptManager - it has been deprecated. You are now to use the "standard" ScriptManager (hooray for all!!!!).
So, a minimal working example will look like this:
Markup: (this is not a master/child page setup).
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<h3>Select A Hotel</h3>
<asp:TextBox ID="TextBox1" runat="server" Width="254px"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender"
runat="server" BehaviorID="TextBox1_AutoCompleteExtender"
DelimiterCharacters="" TargetControlID="TextBox1"
CompletionInterval="100"
MinimumPrefixLength="1"
ServiceMethod="SearchCustomers" >
</ajaxToolkit:AutoCompleteExtender>
</div>
</form>
</body>
So, note how we use the standard script manager. (you should not even see the older script manager in the tool box anyway - as noted, it is depreciated (it caused too many issues - and having two script managers on the same page amounts to a really big hairy ball of js code anyway).
So, so with above, then we need our routine.
This works for me:
[WebMethod()]
public static List<string> SearchCustomers(string prefixText, int count)
{
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL = "SELECT HotelName FROM tblHotels " +
"WHERE HotelName like #SearchText + '%' ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Parameters.Add("#SearchText", SqlDbType.NVarChar).Value = prefixText;
conn.Open();
SqlDataReader sReader = cmdSQL.ExecuteReader();
while (sReader.Read())
customers.Add(sReader["HotelName"].ToString());
}
}
return customers;
}
And the result is this - I typed in K and a drop pop does show:
So, if you have the older ajax script manager? I would suggest and attempt to update (upgrade) to a newer version of ajaxtoolkit - since you now only need one script manager for pages.
You can use nuget for this. (but, I can't recall the details, but upgrading a existing site had some issues. But, it was WELL WORTH the efforts to get this down to use one common and standard ScriptManager - and not two of them.
The only perhaps "issue" in your code? does this return a list of string??
dccfields = DCC.get_field_names();
OFControls.get_autocomplete_list(dccfields, prefix);

Related

Populate table column from code foreach row

I recently started the transition from asp.net webforms to blazor server side.
I am still reading and learning about it, and as a side project in order to learn, i started to rewrite an application i made in webforms.
So, in the webforms, when i had to present very big amounts of data coming from ms sql server, i used asp:repeater to populate the main values, and then with nested update panels i managed to have the basic results almost instantly, and after 1-2 seconds, the other columns were populated.
I try to do something similar with Blazor, but with no luck at all.
My code for the main values is
<tbody>
#if(antists==null)
{
}
else
{
#foreach (var antist in antists)
{
string? trdr = "405";
string? mtrl = antist.Mtrl;
string? trdbusiness = "2001";
string? mtrpcategory = antist.Mtrpcategory;
string? mtrmanfctr = antist.Mtrmanfctr;
string image = "https://zerog01.b-cdn.net/" + antist.Image_guid + ".jpg";
//getfldasync(trdr, mtrl, trdbusiness, mtrpcategory, mtrmanfctr);
<tr>
<td style="text-align: center">
<a data-fancybox href=#image>
<img id="img_eikona_in" runat="server" class="img-fluid" style="max-height:100px;"
src=#image onerror="this.onerror=null; this.src='/webimages/no-image.jpg'" /></a>
</td>
<td>#antist.Code.ToString() <br>
#antist.Name</td>
<td>#fld</td>
</tr>
}
}
</tbody>
My goal is to populate #fld from a stored procedure. If i use code to do this on the fly as the rows are being created, it is very slow. (same problem as webforms)
I tried to use async method, but no luck. The closer i got was to have System.Threading.Tasks.Task`1[System.String] shown in the column of #fld. I didn't keep the exact code, but it was something like
public async Task<string> getfldasync(string trdr, string mtrl, string trdbusiness, string mtrpcategory, string mtrmanfctr )
SqlCommand cmd = new SqlCommand(str, con_digi);
cmd.Parameters.AddWithValue("#trdr", trdr);
cmd.Parameters.AddWithValue("#mtrl", mtrl);
cmd.Parameters.AddWithValue("#trdbusiness", trdbusiness);
cmd.Parameters.AddWithValue("#mtrpcategory", mtrpcategory);
cmd.Parameters.AddWithValue("#mtrmanfctr", mtrmanfctr);
await con_digi.OpenAsync();
var scalar = cmd.ExecuteScalarAsync();
fld = Convert.ToString(scalar);
await con_digi.CloseAsync();
return fld;
>not a sp, but i wanted to make changes in order to test the code.
Is there another method i miss for presenting that kind of data? Or should i keep on trying to make async call?
Edit: I uploaded the code where i used datatable instead of list for the initial databind of the table.

Using C# Script in SharePoint Page

I've done quite a bit of searching (several hours actually) but I haven't been able to get this working. Basically, I have this button:
<asp:Button runat="server" Text="Go!" id="go" onClick="getDoc()" />
and this block of script:
<script type="c#" runat="server">
public void getDoc(object sender, EventArgs e) {
// Test to see if function was running (it's not...)
DocFrame.Attributes["src"] = "http://www.google.com";
// Get the current state of the dropdowns
String dropYear = (String)Year.SelectedValue;
String dropDiv = (String)Division.SelectedValue;
String dropControl = (String)Control.SelectedValue;
String dropQuart= (String)Quarter.SelectedValue;
// Get the Site where the list is
using (SPSite siteCol = new SPSite("http://portal/Corporate/IT/")) {
using (SPWeb web = siteCol.RootWeb){
// Get the list items we need
SPListItemCollection items = list.GetItems("Year", "Division", "Control", "Quarter");
SPListItem item = null;
// Loop through them until we find a matching everything
foreach (SPListItem it in items){
if(it.Year == dropYear && it.Division == dropDiv && it.Control == dropControl && it.Quarter == dropQuart){
item = it;
break;
}
}
// Assign the item as a string
String URL = (String)item["Title"];
// Set the iframe to the new URL
DocFrame.Attributes["src"] = URL;
}
}
}
It's all in the page where this is happening, please keep in mind that I've been using sharepoint for less than a week and have only ever coded in C++, so I could be doing everything horribly wrong. Anyway, it seems that getDoc() is never even getting called, so can anyone point out what I'm doing wrong?
Instead of
onClick="getDoc()"
you should do
OnClick="getDoc"
That's the proper way to wire an up an event.
By the way, you should consider following C# Naming Guidelines. If you were using better naming, it might look like this:
<asp:Button runat="server" Text="Go!" id="GoBtn" onClick="GoBtn_Click" />
Common practice convention is to append the event name after the ID of the control. It's not required, but it looks cleaner and other developers like to see that when they look at your code.
Also, DocFrame.Attributes["src"] = "http://www.google.com"; is not a good way to see if the function is running. It doesn't update the page in realtime, as the entire server side function executes, then the results are sent to the client. Instead, use your IDE's debugging tools to hook up to the server and set code breaks etc. Or what I do is have the code send me an email, I created a little utility library for that.

Ajax autocomplete extender not working in asp.net c#

I read many posts regarding the issue, but couldnt locate my mistake. Can anybody please help
Ajax autocomplete extender is not working
aspx.cs file
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static List<string> getMemberInfo1(string prefixText)
{
List<string> firstName = new List<string>();
DataTable table = new DataTable();
table = admObj.getMemberInfo(prefixText);
for (int i = 0; i < table.Rows.Count; i++)
{
firstName.Add(table.Rows[i][2].ToString() + " - " + table.Rows[i][0].ToString() + " " + table.Rows[i][1].ToString());
}
return firstName;
}
aspx file
<asp:TextBox ID="ReferralIdTextBox" runat="server" Width="200px"
AutoCompleteType="DisplayName" AutoPostBack="True" ></asp:TextBox>
<asp:AutoCompleteExtender ID="ReferralIdTextBox_AutoCompleteExtender"
runat="server" Enabled="True"
TargetControlID="ReferralIdTextBox"
ServiceMethod="getMemberInfo1">
</asp:AutoCompleteExtender>
If I copy paste the same code in a new file, it works fine there.
Has is got to anything with the rest of the functions on page?
I think there are two or three things missing. You have not mentioned service path in your code. Another thing is you need to add script manager for this.
So, Please go through following link and put missing things.
http://www.codeproject.com/Articles/201099/AutoComplete-With-DataBase-and-AjaxControlToolkit

c#.net postback of form not keeping 1 value

Having a strange problem regarding the postback of a form I've created. The answer will probably be really simple, but I can't seem to see it.
I have a form that a user can fill in if the page a video is on, isn't working. It pre-populates fields based on the current video selected, and allows the user to fill in other fields, and send the email to me for support.
The problem
The fields are pre-populated correctly, but one of the fields 'Page', although pre-populated correctly, doesn't pass the value to the button submit method.
the clientside code
(includes some mootools javascript, this works)
<asp:Panel ID="pnlVideoProblem" runat="server" Visible="false">
<h2>Report a video/learning tool issue</h2>
<div class="keyline"></div>
<fieldset class="emailform">
<ul>
<li><label>Name <span class="error">*</span></label><asp:TextBox ID="txtVideoName" runat="server" MaxLength="60"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator33" runat="server" CssClass="error" ControlToValidate="txtVideoName" ErrorMessage="Required"></asp:RequiredFieldValidator></li>
<li><label>Email <span class="error">*</span></label><asp:TextBox ID="txtVideoEmail" runat="server" MaxLength="100"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator35" runat="server" CssClass="error" ControlToValidate="txtVideoEmail" ErrorMessage="Required"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator7" runat="server" ControlToValidate="txtVideoEmail" Text="Invalid email" ErrorMessage="Email address is not in the correct format" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator></li>
<li><label>OTHER FIELD</label><asp:TextBox ID="txtOtherField" runat="server" MaxLength="10"></asp:TextBox></li>
<li><label>Video ID</label><asp:TextBox ID="txtVideoID" runat="server" ReadOnly="true"></asp:TextBox></li>
<li><label>Browser/Version </label><asp:TextBox ID="txtVideoBrowser" runat="server" MaxLength="100"></asp:TextBox></li>
<li><label>Flash Version </label><asp:TextBox ID="txtFlashVersion" runat="server"></asp:TextBox></li>
<li><label>Page </label><asp:TextBox ID="txtVideoPage" runat="server"></asp:TextBox></li>
<li><label>Visible error messages </label><asp:TextBox ID="txtVisError" runat="server" TextMode="MultiLine" Rows="6" MaxLength="4000"></asp:TextBox></li>
</ul>
<asp:Button ID="btnSubmitVideoIssue" runat="server" CssClass="subbutton" Text="Submit report" OnClick="btnSubmitVideoIssue_Click" />
</fieldset>
<script type="text/javascript">
window.addEvent('domready', function () {
document.id('<%= txtVideoBrowser.ClientID %>').set('value', Browser.Platform.name + ", " + Browser.name + " " + Browser.version);
document.id('<%= txtFlashVersion.ClientID %>').set('value', Browser.Plugins.Flash.version + "." + Browser.Plugins.Flash.build);
});
</script>
</asp:Panel>
the page-behind code for the button
(there is no reseting of the values on postback)
protected void btnSubmitVideoIssue_Click(object sender, EventArgs e)
{
if (CheckEmptyCaptcha() == false)
{
//this field is hidden in css and empty. if it has been filled in, then an automated way of entering has been used.
//ignore and send no email.
}
else
{
StringBuilder sbMessage = new StringBuilder();
emailForm = new MailMessage();
sbMessage.Append("Name : " + txtVideoName.Text.Trim() + "<br>");
sbMessage.Append("Email : " + txtVideoEmail.Text.Trim() + "<br>");
sbMessage.Append("Other Field : " + txtOtherField.Text.Trim() + "<br>");
sbMessage.Append("Video ID : " + txtVideoID.Text.Trim() + "<br>");
sbMessage.Append("Browser : " + txtVideoBrowser.Text.Trim() + "<br>");
sbMessage.Append("Flash Version : " + txtFlashVersion.Text.Trim() + "<br>");
sbMessage.Append("Visible error messages : " + txtVisError.Text.Trim() + "<br>");
sbMessage.Append("Url referrer : " + txtVideoPage.Text.Trim()+"<br>");
sbMessage.Append("Browser : " + Request.UserAgent + "<br>");
if (txtVideoBrowser.Text.Contains("ie 6"))
{
sbMessage.Append("<strong>Browser note</strong> : The PC that made this request looks like it was using Internet Explorer 6, although videos work in IE6, the browser isn't stable software, and therefore Javascript errors may occur preventing the viewing of the page/video/learning tool how it was intended. Recommend that the user upgrades their browsers to the latest version of IE.<br>");
}
Double flashver = 0.0;
if(Double.TryParse(txtFlashVersion.Text, out flashver))
{
if(flashver < 9.0)
{
sbMessage.Append("<strong>Flash version note</strong> : The PC that made this request is currently using flash version "+flashver+". Flash version 9 or greater is required to view videos. Recommend user upgrades their flash version by visiting http://get.adobe.com/flashplayer<br>");
}
}
else
{
sbMessage.Append("<strong>Flash version note</strong> : It doesn't look like flash is installed on the PC that made this request. Flash is required to view videos . Recommend user installs flash by visiting http://get.adobe.com/flashplayer<br>");
}
emailForm.To.Add(new MailAddress("admin#test.com"));
emailForm.From = new MailAddress(txtVideoEmail.Text.Trim(), txtVideoName.Text.Trim());
emailForm.Subject = "[ERROR] - [VIDEO ISSUE] from " + txtVideoName.Text.Trim();
emailForm.Body = sbMessage.ToString();
emailForm.IsBodyHtml = true;
bool sendSuccess = false;
try
{
SmtpClient smtp = new SmtpClient();
smtp.Send(emailForm);
sendSuccess = true;
}
catch
{
pnlVideoProblem.Visible = false;
pnlFailure.Visible = true;
ltlFailure.Text = "There was a problem sending your feedback, please go back and try again.";
}
finally
{
if (sendSuccess)
{
pnlVideoProblem.Visible = false;
pnlSuccess.Visible = true;
ltlSuccess.Text = "Thank you, your feedback has been sent. Click close to return to the website.";
}
else
{
pnlVideoProblem.Visible = false;
pnlFailure.Visible = true;
ltlFailure.Text = "There was a problem sending your feedback, please go back and try again.";
}
}
}
}
the form values
Name : User
Email : User#test.com
Other Field : aab123
Video Learning ID : 5546
Browser version : win, firefox 9
Flash version : 11.102
Page : https://www.awebsite.com/library/video/5546
Visible error messages : ewrwerwe
the resulting email
Name : User
Email : user#test.com
Other Field : aab123
Video ID : 5546
Browser : win, firefox 9
Flash Version : 11.102
Url referrer :
Visible error messages : ewrwerwe
Video ID and Page/Url Referrer are populated on (!IsPostBack)
(!IsPostBack)
pnlVideoProblem.Visible = true;
if (!String.IsNullOrEmpty(Request.QueryString["vid"]))
{
txtVideoID.Text = Request.QueryString["vid"];
}
if (!String.IsNullOrEmpty(Request.QueryString["other"]))
{
txtOtherField.Text = Request.QueryString["other"];
txtOtherField.ReadOnly = true;
}
txtVideoPage.Text = HttpUtility.UrlDecode(Request.QueryString["ref"]);
txtVideoPage.ReadOnly = true;
any ideas? I have a brick wall i can hit my head against based on how simple the answer is.
If TextBox's ReadOnly property is "true", postback data won't be
loaded e.g it essentially means TextBox being readonly from
server-side standpoint (client-side changes will be ignored).
If you want TB to be readonly in the "old manner" use:
TextBox1.Attributes.Add("readonly","readonly")
as that won't affect server-side functionality.
From: http://aspadvice.com/blogs/joteke/archive/2006/04/12/16409.aspx
See also: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.readonly.aspx
Solved :)
After a tiny ray of sunshine i remembered I had this
RewriteRule ^/pop/(.*[^/])/report-issue/([a-fA-F0-9]{32})-([0-9]+)$ /pop.aspx?tp=$1&pg=report-issue&vid=$2&other=$3&ref=%{HTTP_REFERER} [L]
as a rewrite rule, which then led me to take a closer look at whether the form fieldswere actually was wrapped in a postback. Lo-and-behold, they werent.
I've wrapped a !postback around the querystring variable reading section and it works!
brick wall needs to be very thick.
thanks to those that tried to help!

Using Programmatic Images in Nivo SLider with asp.net and c#

"Only images or images wrapped in links are allowed in the slider div. Any other HTML will break the slider."
What would be the best way to programatically insert images from a database in c#?
I was using a label inside the div id="slider" tag but then realized the label would create the images within a span tag and therefore break the slider.
lblSlider.Text += "<img src=\"" + URL + "\" alt=\"" + address + "\" title=\"<a href='Featured/" + address" + address + ", " + city + "</a>\" />";
Use markup like this...
<img src='ImageHandler.ashx?ProductID=<%# Eval("ProductID")%>'
alt="<%# Eval("ProductName") %>" title="<%# Eval("ProductName") %>" />
... in conjunction with an image HttpHandler class like this (adapt for your own particular DB schema):
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["productID"] != null)
{
try
{
string ProductID = context.Request.QueryString["ProductID"];
if (Convert.ToInt32(ProductID) > 0)
{
const string CONN
= "Initial Catalog=xxx;Data Source=xxx;Integrated Security=SSPI;";
string selectQuery
= "SELECT Photo FROM dbo.Products WHERE dbo.Products.ProductID="
+ ProductID.ToString();
SqlConnection conn = new SqlConnection(CONN);
SqlCommand cmd = new SqlCommand(selectQuery, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
dr.Close();
conn.Dispose();
// context.Response.End();
// caused an "Abort thread" error
// - this is correct and is a special exception
}
}
catch (Exception ex)
{
ErrorReporting.LogError(ex);
}
}
else
throw new ArgumentException("No ProductID parameter specified");
}
public bool IsReusable
{
get
{
return true; // multiple images otherwise false
}
}
}
Okay, I haven't tried the other solution but I did this and it works:
Here are some global c# variables:
protected int count;
protected string[] arr = new string[20];
Then I assign values to the string array from my database in the Page_Load method.
And then I just write the nivo slider with javascript on my page:
<script type="text/javascript">
document.write("<div id='slider' class='nivoSlider'>");
var count = <%= count %>;
var myArray = <% = new JavaScriptSerializer().Serialize(arr) %>;
for(var i = 0; i < count; i++) {
document.write(myArray[i]);
}
document.write("</div>");
</script>
This solution seems easier to me, but if anyone thinks I should use the other solution over this one, let me know. Oh, and don't forget the namespace System.Web.Script.Serialization
I have same requirement and tried the below code to accomplish the dynamic loading of images basing on category. These image loaded from my database. I am new to ASP.Net please let me know if I did anything wrong or did any blunders :).
in ASP.Net file:
I am using nivo slider append method
<script type="text/javascript">
$(window).load(function() {
$('#slider').append('<img id="ad5" src=<%=__ad1ImageUrl %> />');
$('#slider').append('<img id="ad6" src=<%=__ad2ImageUrl %> />');
$('#slider').append('<img id="ad7" src=<%=__ad3ImageUrl %> />');
$('#slider').append('<img id="ad8" src=<%=__ad4ImageUrl %> />');
$('#slider').nivoSlider();
});
</script>
My table looks like this:
<table style="height: 183px; width: 100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td align="left">
<div id="wrapper">
<div class="slider-wrapper theme-default">
<div class="ribbon">
</div>
<div id="slider" class="nivoSlider">
<!-- note that no images added here -->
</div>
</div>
</div>
</td>
</tr>
</table>
In the code behind:
Use variable to store image url(s). You can now get the URL(s) from DB and get populated. In my code i have used these variables (can use array also) to capture url path. You can get the paths from any source like Database, Xml or ...
public string __ad1ImageUrl = "";
public string __ad2ImageUrl = "";
public string __ad3ImageUrl = "";
public string __ad4ImageUrl = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
__ad1ImageUrl = "UserControls/Images/mainBanner1.jpg";
__ad2ImageUrl = "UserControls/Images/mainBanner2.jpg";
__ad3ImageUrl = "UserControls/Images/mainBanner3.jpg";
__ad4ImageUrl = "UserControls/Images/mainBanner4.jpg";
}
}

Categories