Hope someone can help with this. I've been up and down the web and through this site looking for an answer, but still can't get the Autocomplete AJAX control to work. I've gone from trying to include it in an existing site to stripping it right back to a very basic form and it's still not functioning. I'm having a little more luck using Page Methods rather than a local webservice, so here is my code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="droptest.aspx.cs" Inherits="droptest" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
MinimumPrefixLength="1" ServiceMethod="getResults"
TargetControlID="TextBox1">
</cc1:AutoCompleteExtender>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Services;
using System.Web.Services;
public partial class droptest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public string[] getResults(string prefixText, int count)
{
string[] test = new string[5] { "One", "Two", "Three", "Four", "Five" };
return test;
}
}
Tried to keep things as simple as possible, but all I get is either the autocomplete dropdown with the source of the page (starting with the <! doctype...) letter by letter, or in IE7 it just says "UNDEFINED" all the way down the list.
I'm using Visual Web Developer 2008 at the moment, this is running on Localhost. I think I've exhausted all the "Try this..." options I can find, everything from adding in [ScriptMethod] to changing things in Web.Config.
Is there anything obviously wrong with this code?
Only other thing that may be having an effect is in Global.asax I do a Context.RewritePath to rewrite URLs - does this have any effect on AJAX?
Thanks for any help you can give.
You also need to include your page name as the servicePath, I think.
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
MinimumPrefixLength="1" ServiceMethod="getResults" ServicePath="droptest.aspx"
TargetControlID="TextBox1">
</cc1:AutoCompleteExtender>
Try adding ServicePath to the cc1:AutoCompleteExtender with the path to the web service.
[WebMethod, ScriptMethod]
public string[] getResults(string prefixText, int count)
{
be sure to include the ScriptMethod attribute.
Right, something I've added in from these suggestions has worked!!! Still have a problem though, it works in a standalone project but adding it back into the existing project and it's not working again. So thanks for the help so far, I have a working example, just have to figure out what is killing it inside the other project now.
Make the method static:
[WebMethod]
public static string[] getResults(string prefixText, int count)
{
string[] test = new string[5] { "One", "Two", "Three", "Four", "Five" };
return test;
}
Update:
A shot in the dark... try moving the ScriptManager above the textbox. Also, I would set the ServicePath to "~/" simply because you mention the URL rewrites.
If you are using IIS 5.1, try to temporarily remove .* from the application setting. This wildcard setting prevents AJAX like control to work correctly.
In my case, my project use rewrite rule to remove the extension aspx. I thing the problem is that. I comment the rewrite rule in web.config. Then clear solution. Rebuild it. Clear all history in firefox / chrome (what you use). Then Ctrl+F5 or F5. Autocomplete show correctly.
Related
I've been doing some really clever stuff (I think) in ASP.Net c#, so much so that the simple stuff is more difficult (if that makes sense)
I have this snippet of code in my page
<form id="form1" runat="server">
<asp:HiddenField runat="server" ID="hdnConfirm" value="Hello World" />
<asp:LinkButton runat="server" PostBackUrl="/confirm.aspx" Text="Confirm">
</asp:LinkButton>
</form>
I have this snippet of code in confirm.aspx.
if !(IsPostback)
{
lblConfirm.Text = Request.Form["hdnConfirm"]
}
I was expecting this to be nice and simple but when i click the button and go to page "confirm.aspx" the Request.Form has no values. What have I missed ?
[TESTING]
I ran a test on a brand new web forms project in VS2013. Dot.Net 4.5.1 This does not work. PreviouPage is always null. Whether surrounded by (!IsPostBack) or not. Doesn't matter if the submitting control is a Button, LinkButton or Hyperlink. Request.Form["hdn"] is also null. I have restarted my computer just in case and still no joy. I am missing something really simple I am sure of it but I can't see what
This is the first page nothing in the code behind
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LinkButton runat="server" PostBackUrl="~/WebForm2.aspx">click</asp:LinkButton>
<asp:HiddenField runat="server" ID="hdn" Value="3" />
</div>
</form>
</body>
</html>
This is the second page
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication2.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string s = ((HiddenField)this.PreviousPage.FindControl("hdn")).Value;
}
}
}
On confirm.aspx use PreviousPage.FindControl instead :
HiddenField hdnFieldName = this.PreviousPage.FindControl("hdnConfirm") as HiddenField;
string hiddenValue = string.Empty;
if (hdnFieldName != null)
{
hiddenValue = hdnFieldName.Value;
}
Here is good example to get you started.
What's going on Here:
By default with VS 2013 and Asp.Net v4.5.1 , there is a feature FriendlyUrls which is enabled.
The FriendlyUrls feature does kind of Asp.Net routing , thus changing URLs from localhost/webform1.aspx to localhost/webfrom1
PostbackUrl property will not work in combination with Asp.Net Routing. When ASP.NET routing is in use the PreviousPage URL is the final routed URL. The runtime will check for a file represented by the Routed URL now, which will be webform1 and NOT webfrom1.aspx. Since there is NO such file as webform1, so it will always set the PreviousPage to null.
Possible Solutions:
So, now you know the issue at hand.
1.) Either don't use the Routing system of Asp.Net Friendly Urls , in this case, therefore try adding the <%# PreviousPageType VirtualPath="~/WebForm1.aspx"%> to webform2.aspx page and check.
2.) OR if you keep the FriendlyURLs and hence the Routing system, make changes in your code to read the Form values using some other alternatives.
I am trying to get the AjaxControlToolkit (ACT) Auto complete extender working.
It was working briefly but has now stopped working and I can't figure out why. I haven't changed changed anything in my project that I can see would affect this.
I have even created a brand new VS2013 project and tried to implement this but still no joy.
I see several references to "ajaxToolkit:ToolkitScriptManager" but I cannot find a reference for this anywhere. I have tried installing the toolkit from a download as well as via NUGET and it simply will not work.
I have tried every example on here, at least 20 of them or more and still not joy. If you have it working please post your code because mine doesn't work and its pointless posting it be cause i have tried absolutely everything suggested here
Any help would be much appreciated as I really dont want to engineer something unelegant to get around this.
Thanks loads
[UPDATE]
ToolkitScriptManager is removed from ACT 15.1 see here So that answers this question but the autocomplete still is not working
[UPDATE]
Here is an example I put togetgher, which still does not work with or without the [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()] directive
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestWebSite.WebForm1" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="GetCompletionList"
MinimumPrefixLength="1"
CompletionInterval="100"
ID="AutoCompleteExtender1"
runat="server"
TargetControlID="TextBox1"></cc1:AutoCompleteExtender>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestWebSite
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
string[] s = {"a","b","c","d"};
return s;
}
}
}
You need to register the AJAX Control Toolkit Library by putting the following line just below the #PageDirective
this is the ajaxtoolkit
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
then this is the example to call ajaxtoolkit
<cc1:toolkitYouWantToUse/>
thasts it
Ok I have it working. I created a brand new test projects in VS2013. I used the developer features of Google Chrome to debug and saw I was constantly getting a 500 error. In my experience I've usually caused this by getting my web addresses wrong so that led me to checking that the web service was working. (See further down)
After fixing that problem and knowing that the web service was OK I engaged in some trial and error, and the steps below solved the problem. I now have the AutoCompleteExtender working in all my projects using this same method.
(This may not be the way to do it but I know it works for me)
Remove the nuget installed version of the AjaxControlToolkit (ACT)
Manually add the reference to the ACT dll that I had downloaded, get the latest version from here.
Add a .asmx file to your project with the WebMethod defined as below. You can actually call the method any name you like the profile (e.g. parameters and return type) must remain the same. There may be other variations but I don't know what they are. I just know that this configuration worked for me.
Re-add the AutoCompleteControl. the VS IDE will add the #Register directive for you
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="GetCompletionList"
ServicePath="WebService1.asmx"
MinimumPrefixLength="0"
CompletionInterval="100"
ID="AutoCompleteExtender1"
runat="server"
TargetControlID="TextBox1"></cc1:AutoCompleteExtender>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace TestWebSite
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string[] GetCompletionList(string prefixText, int count)//, string contextKey)
{
string[] s = { "a", "b", "c", "d" };
return s;
}
}
}
//List<string> works just as well as string[]
Run the project, manually navigate to the .asmx page and make sure that the function returns the results you expect. VS knows your running in debug so will let you add parameters and call the web method.
I am deploying a site built as a set of projects in a solution which is deployed as a series of websites (one project = one url).
The coding lanague is c# and the site uses a mssql db accessed via linq.
Everything works ok on the development server but at the moment, all pages with dynamically created elements (i.e all <asp> and custom tags) output a blank page with the following source code. Static pages (standard html and aspx) display correctly.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content="text/html; charset=windows-1252" http-equiv=Content-Type></HEAD>
<BODY></BODY></HTML>
I normally work with php on LAMP and this behaviour is unlike anything I've seen in that setup. I need some fresh ideas on causes / resolution of this error (preferably step by step / tutorial links - like I say IIS/c#.net is not my normal enviroment).
Things I have tried with no effect whatsoever:
altering permissions on site folders
altering web.config settings
Redeploying site files via copy / paste and the vb publish option with various settings
Plus a whole ton (over two days so far) of internet research
Thanks for all replies.
edit:
version numbers:
iis: v6.1 (bulid: 7601)
OS: Windows web server 2008 R2 / Service pack 1
.net: v4
second edit:
Sample page:
aspx file:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="dbtest.aspx.cs" Inherits="Rica.Yoodul.dbtest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>test</h1>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace Rica.Yoodul
{
public partial class dbtest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RicaConnectionString"].ConnectionString);
myConnection.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("SELECT * FROM dbo.MaritialStatus", myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Literal1.Text = Literal1.Text + myReader["Name"].ToString();
}
myConnection.Close();
}
}
}
edit:
Something I didn't add: Based on some of the other behaviour the server is displaying, I think the most likely culprit is misconfiguration of the server.
edit:
OK I've narrowed down the cause a little. By taking out everything except the langauge attribute in the first line of the front end file I can get the server to display the static content.#
edit:
OK http://www.iis.net/ConfigReference covers the use of the iis config files. Only I went to the path indicated on the page and I don't appear to have any config files at all. How do I comfirm / fix this?
It sounds like your production server doesn't have ASP.NET correctly installed/registered, so your pages are being treated as simple text documents rather than code. This can sometimes happen if you install .NET before installing IIS, for example.
To confirm this, put together a barebones page that includes a mix of HTML and ASP.NET...
<%# Page Language="C#" %>
<html>
<head>
<title>ASP.NET Hello World</title>
</head>
<body>
<p>Hello from HTML</p>
<p><%= "Hello from ASP.NET" %></p>
</body>
</html>
If you load that up and only get the plain-HTML greeting, use your browser's "View Source" option and see what you're actually getting. If your ASP.NET source-code is shown in the source the browser's receiving, that confirms that IIS didn't treat it as an ASP.NET file - which means ASP.NET isn't installed correctly or is disabled.
I am attempting to let a client upload a file to my server in an ASP.NET C# website. I have created a simple script to introduce myself to the nuances of both uploading a file and also creating a script where all the code (HTML and C# code) is in the same file.
My Problem: The function uploadFile() never outputs/returns any string result when it should return a string describing if the upload succeeded or why it failed.
What am I doing wrong?
PS: I have updated my web.config with the following code:
<appSettings>
<add key="folderPath" value="uploadedFiles"></add>
</appSettings>
PPS: Is there anything wrong with having my C# code & HTML all in the same .aspx file? Is it better to separate them out?
My Simple Code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="WebApplication1.test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/C#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
protected global::System.Web.UI.HtmlControls.HtmlInputFile fileUpload;
protected global::System.Web.UI.WebControls.Label lblMessage;
protected global::System.Web.UI.WebControls.Button btnSave;
protected global::System.Web.UI.HtmlControls.HtmlGenericControl test;
protected void bt1Clicked(Object sender, EventArgs e)
{
if (fileUpload.PostedFile != null)
{
string strFilename, strMessage;
strFilename = fileUpload.PostedFile.FileName.ToString();
strMessage = uploadFile(strFilename, ConfigurationManager.AppSettings["folderPath"]);
output.InnerHtml = strMessage;
}
}
public string uploadFile(string fileName, string folderName)
{
if (fileName == "")
{
return "Invalid filename supplied";
}
if (fileUpload.PostedFile.ContentLength == 0)
{
return "Invalid file content";
}
fileName = System.IO.Path.GetFileName(fileName);
if (folderName == "")
{
return "Path not found";
}
try
{
if (fileUpload.PostedFile.ContentLength <= 2048000)
{
fileUpload.PostedFile.SaveAs(Server.MapPath(folderName) + "\\" + fileName);
return "File uploaded successfully";
}
else
{
return "Unable to upload,file exceeds maximum limit";
}
}
catch (UnauthorizedAccessException ex)
{
return ex.Message + "Permission to upload file denied";
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="fileUpload" type="file" Runat="server" NAME="fileUpload"/>
<asp:button id="btnSave" runat="server" Text="Upload File" OnClick="bt1Clicked"></asp:button>
<p id="output" runat="server">Result should be displayed here after clicking</p>
</div>
</form>
</body>
</html>
If you're going to put your C# code in the front page, you'll need to put it in a <script runat="server"> tag. When I do this (which is very rarely), I'll usually put the <script> tag after the HTML. For example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
...
</html>
<script runat="server">
//Code here
</script>
The advantage of using <script runat="server"> is that if you are writing a Web Application (where the code compiles into a dll), you can create pages that run server side without doing a new build of the application (of course you'll have to remove the CodeBehind attribute from the #Page directive). So if you're in a situation where you can't do a new build for whatever reason, writing everything in the .aspx for a one off page can be useful.
That being said, you're probably better off writing the code in the codebehind file (In your case this is test.aspx.cs, and you can get to it in VS.NET by right clicking on test.aspx in the Solution Explorer and selecting "View Code" or by pressing F7 when you're viewing the test.aspx file). Using the codebehind file separates the code from the HTML, and more importantly compilation errors will be raised when you compile the application. If you use <script runat="server">, compilation errors won't be raised until the page is accessed.
In answer to your PPS - yes in general it is considered best practice to have your C# code in a separate file. There are a few reasons for this, I'll list a few here for you:
Ease of maintenance - having the C# in another file makes it easier to fix or change things later
Easier for UI guys to work with - If you're working with a designy type person who's doing your HTML and CSS etc, it'll be easier for them to work with the mostly-html ASPX markup, without all the C# getting in the way
Precompiling - Your C# code can be precompiled away into a DLL if it's in a separate file, but if it's in an ASPX file it needs to be compiled by IIS when it is running.
There's probably a bunch of other reasons that I haven't mentioned too...
Some might say for a simple test/tutorial application you don't need to worry so much, but it's probably best to PRACTICE best practices while you are doing tutorials etc. so it doesn't seem foreign to you later on.
And if you have to put it all in one file for some reason, take rsbarro's advice above and put it in a completely separate block below the HTML so it's nice and clean.
Developing is more of a hobby at the moment; so apologies if this is a basic question, although after a couple of hours searching the web I can't seem to find an answer. I am currenttly building a support tool for my team which runs a number of SQL queries & BCP processes and returns the results. Some of these actions take quite a while and I would like to update the web UI with status messages. Previously I have been using the Label1.Text = text;
However now I would like to update the Label1.text multiple times while my method is running. Try as I might though it only displays the last update in the method.
I have coded a small test to try get to the bottom of this: -
Web Page
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Template._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="progress" runat="server" Text=""></asp:Label><br />
<asp:Image ID="Image1" runat="server" ImageUrl="~/Image/loader.gif"
Visible="False" />
</div>
</form>
</body>
</html>
C# CodeBehind
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace Template
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
uiUpdate("OUT", 1);
wait();
uiUpdate("In", 0);
}
protected void uiUpdate(string text, Int32 image)
{
if (image == 1)
{
Image1.Visible = true;
}
else
{
Image1.Visible = false;
}
progress.Text = text;
}
protected void wait()
{
DateTime wait;
wait = DateTime.Now + TimeSpan.FromSeconds(10);
while (wait > DateTime.Now)
{
}
}
Is there a way I can get the Label1 & Image to update as the Page_load is running?
Or am I looking at this the totally wrong way (no doubt!)
Thanks
HTML as a full page request is not in the least bit granular:
your browser sends a request (of all the form variables, cookies, etc etc) to the server
the server does a bit of processing and sends a response (typically html)
your browser processes the response and renders the display
All your updates are happening in the middle bullet, so no: there is no way to make the browser update: your code is executing on the server, with no dialog with the client
If you need this type of behaviour, you would have to look at AJAX tools - at each step doing "just enough" work to get to the next milestone and update the caption... with regular ASP.NET UpdatePanel may be of interest; for MVC or other (non-ASP.NET) setups, jQuery would be your friend. Unfortunately, this isn't a trivial topic.
If I understand your question correct you can't do this in regular asp.net, you need to use ajax, and make an ajax method in which you then update the text of the label on runtime. You can use the ajax MS scriptmanager to do this.
If it is not for high performance you can use an update panel otherwise you should just use the scriptmanager by yourself.