0

I'm trying to execute a simple Javascript method on a web server generated by C#. I can get the web server to run and generate a simple web page with a button, but I can't seem to get the button to run the js .

Using System;
using System.Net;
using System.Threading;
using System.Linq; 
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web.UI.HtmlControls;
//using System.Web.UI.Page;

namespace SimpleWebServer
{
class Program
{
   static void Main(string[] args)
    {
        WebServer ws = new WebServer(SendResponse, "http://localhost:8080/test/");
       // ClientScript.RegisterStartupScript(page.GetType(), "hwa", "alert('Hello World');", true);    
        Console.WriteLine("A simple webserver. Press a key to quit.");
        Console.ReadKey();
        ws.Stop();

    }

    public static string SendResponse(HttpListenerRequest request)
    {
        ws = WebServer;
     //return string.Format("<HTML><HEAD><script src='D:/Script1.js'></script></HEAD><BODY><INPUT type='button' value='Button' runat='server' id='Button1' onClick='buttonClicked()';></BODY></HTML>)");
       ClientScript.RegisterStartupScript(page.GetType(), "hwa", "alert('Hello World');", true);
        return string.Format("<HTML><HEAD><script= alert('button click called');</HEAD><BODY><INPUT type='button' value='Button' runat='server' id='Button1' onClick='alert('button click called')';></BODY></HTML>)");

The JS script code is as follows:

function buttonClicked() {
    alert('button click called');
}

The Web Server code is as follows:

using System;
using System.Net;
using System.Threading;
using System.Linq;
using System.Text;

namespace SimpleWebServer
{
public class WebServer
{
    private readonly HttpListener _listener = new HttpListener();
    private readonly Func<HttpListenerRequest, string> _responderMethod;

    public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
    {
        if (!HttpListener.IsSupported)
            throw new NotSupportedException(
                "Needs Windows XP SP2, Server 2003 or later.");

        // URI prefixes are required, for example 
        // "http://localhost:8080/index/".
        if (prefixes == null || prefixes.Length == 0)
            throw new ArgumentException("prefixes");

        // A responder method is required
        if (method == null)
            throw new ArgumentException("method");

        foreach (string s in prefixes)
            _listener.Prefixes.Add(s);

        _responderMethod = method;
        _listener.Start();
    }

    public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
        : this(prefixes, method) { }
  //  protected void Button1_Click(Object sender, EventArgs e)
   // {
  //      Button1.Text = "Server click handler called.";
  //  }
    public void Run()
    {
        ThreadPool.QueueUserWorkItem((o) =>
        {
            Console.WriteLine("Webserver running...");
            try
            {
                while (_listener.IsListening)
                {

                    ThreadPool.QueueUserWorkItem((c) =>
                    {
                        var ctx = c as HttpListenerContext;
                        try
                        {
                            string rstr = _responderMethod(ctx.Request);
                            byte[] buf = Encoding.UTF8.GetBytes(rstr);
                            ctx.Response.ContentLength64 = buf.Length;
                            ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                        }
                        catch { } // suppress any exceptions
                        finally
                        {
                            // always close the stream
                            ctx.Response.OutputStream.Close();
                        }
                    }, _listener.GetContext());
                }
            }
            catch { } // suppress any exceptions
        });
    }

    public void Stop()
    {
        _listener.Stop();
        _listener.Close();
    }
}
}
  • The most useful advice I found was here: [link]http://stackoverflow.com/questions/5731224/calling-javascript-function-from-codebehind[/link] I'm not sure of the specifics of the rules here but I have tried immensely to implement it but with limited knowledge on either language I'm stuck – Charlie Adair Mar 30 '15 at 23:08
  • you have a typo in the first line, Using should be lower-case using. not sure it will help though.. – torox Mar 30 '15 at 23:11

1 Answers1

0

The html and javascript is wrong in this line of code

return string.Format("<HTML><HEAD><script= alert('button click called');</HEAD><BODY><INPUT type='button' value='Button' runat='server' id='Button1' onClick='alert('button click called')';></BODY></HTML>)");

it should look like the code below

<HTML>
<HEAD>
    <script>
       alert('button click called');
    </script>
</HEAD>
<BODY>
    <INPUT type='button' value='Button' runat='server' id='Button1' onClick='alert("button click called");'>
</BODY>
</HTML>

Replace your return statment with the code below:

 return string.Format("<HTML> <HEAD><script>alert('button click called');</script> </HEAD> <BODY><INPUT type='button' value='Button' runat='server' id='Button1' onClick='alert("button click called");'></BODY></HTML>");
Arlind Hajredinaj
  • 8,380
  • 3
  • 30
  • 45
  • That is very helpful, whenever the page loads the script runs so I now know that the task is possible... The main issue I am having is getting the server to recognize the button click and run the JS file/command whenever this happens, any idea how this might be possible? I'm currently reading into http listeners etc in an attempt to solve it myself, will post back here if I manage to get anything... – Charlie Adair Mar 31 '15 at 14:54