Ajax autocomplete extender not working in asp.net c# - 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

Related

ASP.NET AJax Toolkit AutoCompleteExtender Issue

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);

How to change aspx html heading from code behind?

This is my heading that i want to change from my c# code
<h3>Please Enter a number between 1 &
<asp:Label ID="lbl_max" runat="server"></asp:Label>
</h3>
I want to replace it with a string
string message = "This is new heading...";
i was thinking about something like this
lbl_max.value = message;
But it's not working... I am absolutely new to asp.net, so forgive me if it's a stupid question...
You can do it like this:
this.lbl_max.Text = "This is new heading...";

How to create a content management system using asp.net? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to create a retail website of musical instruments just for practice. To summarize my project, Basically the customer can browse through the selection of instruments, while the admin has additional access to the Content Management System that I'm trying to do in the website. Then the admin can add or remove new/old products and has also an overview of all the items via Gridview.
The general idea for my CMS is, for example I have guitar brands called "Ibanez" and "Fender"(each having their own Griview since their database are separated). I created a webpage where the admin will require to fill up all the necessary details inside the textbox in order to create an item within "Ibanez" and "Fender" or to create entirely a new brand with new items. If the admin is already finish with the info, just click save and finally the new brand or new product will appear in the website. So let's say if the admin wants to create a new brand called "Gibson", the program should automatically create a gridview for that brand in the overview section of my website.
Now in order to achieve all this, What I did was when the admin hits save to create new brands or products, I created a code where it would modify/write new code in some of the project files. It is even programmed to create new files just by adding the .cs or .aspx extension, and then it will just use streamwriter to wirte the new code inside the new file.
Here is sample of my code where you write new code in a file:
var gridViewLines = File.ReadAllLines(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\OverviewGuitarData.aspx");
var _gridViewLines = new List<string>(gridViewLines);
int index = counter;
index -= 1;
_gridViewLines.Insert(index++, "");
_gridViewLines.Insert(index++, " <h3>"+brand_name+" Guitar Items Data</h3>");
_gridViewLines.Insert(index++, " <div style=\"overflow:auto; width:1100px; max-height:500px;\">");
_gridViewLines.Insert(index++, " <asp:GridView ID=\"Guitar" + brand_name + "GridView\" runat=\"server\" CssClass=\"mydatagrid\" PagerStyle-CssClass=\"pager\" HeaderStyle-CssClass=\"header\" RowStyle-CssClass=\"rows\" AllowPaging=\"True\" AllowSorting=\"True\" AutoGenerateColumns=\"False\" CellPadding=\"3\" CellSpacing=\"3\" DataKeyNames=\"id\" DataSourceID=\"SqlDataSource"+brand_number+"\" OnRowDataBound=\"Guitar"+brand_name+"GridView_RowDataBound\" Height=\"250px\" Width=\"864px\">");
_gridViewLines.Insert(index++, " <Columns>");
_gridViewLines.Insert(index++, " <asp:TemplateField>");
_gridViewLines.Insert(index++, " <ItemTemplate>");
_gridViewLines.Insert(index++, " <asp:Button ID=\"Guitar"+brand_name+"GridViewBtn\" runat=\"server\" Text=\"Delete\" OnClick=\"Guitar"+brand_name+"GridViewBtn_Click\"/>");
_gridViewLines.Insert(index++, " </ItemTemplate>");
_gridViewLines.Insert(index++, " </asp:TemplateField>");
_gridViewLines.Insert(index++, " <asp:CommandField ButtonType=\"Button\" ShowEditButton=\"True\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"id\" HeaderText=\"id\" ReadOnly=\"True\" SortExpression=\"id\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"type\" HeaderText=\"type\" SortExpression=\"type\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"model\" HeaderText=\"model\" SortExpression=\"model\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"price\" HeaderText=\"price\" SortExpression=\"price\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"image1\" HeaderText=\"image1\" SortExpression=\"image1\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"image2\" HeaderText=\"image2\" SortExpression=\"image2\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"description\" HeaderText=\"description\" SortExpression=\"description\" ItemStyle-Wrap=\"false\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"neck_type\" HeaderText=\"neck_type\" SortExpression=\"neck_type\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"body\" HeaderText=\"body\" SortExpression=\"body\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"fretboard\" HeaderText=\"fretboard\" SortExpression=\"fretboard\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"fret\" HeaderText=\"fret\" SortExpression=\"fret\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"bridge\" HeaderText=\"bridge\" SortExpression=\"bridge\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"neck_pickup\" HeaderText=\"neck_pickup\" SortExpression=\"neck_pickup\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"bridge_pickup\" HeaderText=\"bridge_pickup\" SortExpression=\"bridge_pickup\" />");
_gridViewLines.Insert(index++, " <asp:BoundField DataField=\"hardware_color\" HeaderText=\"hardware_color\" SortExpression=\"hardware_color\" />");
_gridViewLines.Insert(index++, " </Columns>");
_gridViewLines.Insert(index++, " </asp:GridView>");
_gridViewLines.Insert(index++, " </div>");
gridViewLines = _gridViewLines.ToArray();
File.WriteAllLines(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\OverviewGuitarData.aspx", gridViewLines);
I was successful in this part but when i try to remove a brand, my code did not work and gave me an exception that it is still being used by another process.
Here is the code for removing some text in file:
public static void SearchRemove()
{
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\OverviewGuitarData.aspx");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(" <h3>Gibson Guitar Items Data</h3>"))
{
break;
}
counter+=1;
}
file.Close();
Remove(counter);
}
public static void Remove(int counter)
{
int removeAt = counter;//or any thing you want
removeAt -= 1;
int linesToRemove = 70; //or any thing you want
string s = System.IO.File.ReadAllText(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\OverviewGuitarData.aspx");
List<string> arr = s.Split("\n".ToCharArray()).ToList();
string result = "";
for (int i = 0; i < linesToRemove; i++)
{
arr.RemoveAt(removeAt);
result = "";
foreach (string str in arr)
{
result += str + "\n";
}
System.IO.File.WriteAllText(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\OverviewGuitarData.aspx", result);
}
}
}
When I did not include the removing part, everthing is working fine. I was also informed later on that the approach that I'm doing is risky and not the right way a website works because the admin is modifying contents of a .cs or .aspx file. To be honest I'm stuck in thinking of a better way to do this so my questions is:
1.) How to achieve the above idea without modifying/writing a project file?
OR
2.) If I'm going to continue my previous approach. What algorithm to use if i want to delete the new code that i automatically implemented in the file without getting an exception that states that the process is still being used?
CMSes usually store content in a database or a file system. The code (i.e. a .cs or an .aspx file) is not supposed to store content, it shall contain just the program logic.
Suggestions:
Store your content in a valid XML file. Example:
<?xml version="1.0" encoding="UTF-8"?>
<brands>
<brand name="Gibson">
<items>
...
</items>
</brand>
</brands>
Read the XML file from your ASP.NET program and deserialize it into objects. See also this MSDN topic: https://msdn.microsoft.com/en-us/library/58a18dwa(v=vs.110).aspx.
Fill your GridView or generally speaking your pages with the content you've just retrieved from the XML file.
Setup a watcher on the XML file so that when its content changes you could update your objects and render the new data on your website. See more information about FileSystemWatcher on MSDN: https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx
Having implemented these things, your site won't depend on the code for the contents, instead, it will update every time you update the XML file with the contents. Then you may explore how to store this information in a database instead, so that you could implement some back-end admin page to manage the contents (like most CMSes do).

How can I obtain selected filenames clientside using a fileupload control without submitting?

I can't find an existing answer so far, but here is my goal:
I'd like to use the asp.net fileupload control(or some other control you might suggest) to select a series of files. WITHOUT submitting a form, i'd like the selected files to be displayed in a concatenated list of some sort.
Is this possible with the Fileupload control or do I have to use something else? I've seen many answers involving submission then grabbing the filenames, but I don't want to take a trip to the server for that. Just looking to grab the filenames when they're selected, all clientside.
Thank you for your time!
Using files property. See the code below:
function onInputChange(e) {
var res = "";
for (var i = 0; i < $("#customInput").get(0).files.length; i++) {
res += $("#customInput").get(0).files[i].name + "<br />";
}
$('#result').html(res);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="customInput" type="file" accept="image/*" multiple onchange="onInputChange(event)" />
<br /><br />
<div style="color:blue" id='result'></div>
try this -
Javascript
function showFile() {
var file = document.getElementById("<%=FileUpload1.ClientID%>");
var path = file.value;
alert(path);
}
File Upload Control
<asp:FileUpload ID="FileUpload1" runat="server" onchange="showFile()" />

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!

Categories