Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to send Data from JavaScript to C# Server Code

0.00/5 (No votes)
24 Oct 2014 3  
Sending data from JavaScript Code to ASP.NET C#

Introduction

This blog post describes how to send data from a JavaScript Client to a C# handler on the server. We will guide you through the development of a small ASP.NET application that enables you to send a Json Data from an HTML page to a C# server code handler.

Background

This tip may be useful for intermediate developers who have some basics in C# and .NET.

Using the Code

Through this paragraph, we will have to follow two majors steps:

  • Creating an HTML page and writing some JavaScript Code
  • Writing C# server code on the handler that will receive data sent by JavaScript Code

Steps

  1. Open Visual Studio (This blog post was done by VS 2013.)
  2. Choose C# => Web => ASP.NET Web Application => Empty
  3. Visual Studio 2013 will generate an empty ASP.NET project for you.
  4. Add a new HTML Page and paste this HTML code inside it.
      <label id="From" />How to send Data from JavaScript to C# Handler<br />
        <table>
            <tr>
                <td><label id="From"/>From : </td>
                <td><input id="TxtFrom"></td>
            </tr>
            <tr>
                <td><label id="To"/>To : </td>
                <td><input id="TxtTo" required="required"></td>
            </tr>
            <tr>
                <td><label id="To" />Body : </td>
                <td><textarea id="TxtBody" required="required" 
                rows="10" cols="30"></textarea></td>
            </tr>
            <tr>
                <td/>
                <td style="align-content:flex-end">
                    <button onclick="loadJsonData();">Send Data to the Server</button>
                </td>
            </tr>
    </table>     

    This code is very simple, it draws three inputs used for sending Email. As we all know, we can’t send an email directly via JavaScript and that’s why we will send data to the backend (a C# handler) and we will process it (extract the sender, receiver and the body), once we do this, sending Email with C# will be like a game.

  5. Paste this JavaScript on the same HTML Page:
       function loadJsonData() {
            var postdata = JSON.stringify(
                {
                    "From": document.getElementById("TxtFrom").value,
                    "To": document.getElementById("TxtTo").value,
                    "Body": document.getElementById("TxtBody").value
                });
                try {
                    $.ajax({
                        type: "POST",
                        url: "MailHandler.ashx",
                        cache: false,
                        data: postdata,
                        dataType: "json",
                        success: getSuccess,
                        error: getFail
                    });
                } catch (e) {
                    alert(e);
                }
                function getSuccess(data, textStatus, jqXHR) {
                    alert(data.Response);
            };
                function getFail(jqXHR, textStatus, errorThrown) {
                    alert(jqXHR.status);
            };
        };

    This JavaScript function is very simple, first, we search for the three inputs using ‘getElementById’, once we have data from these three inputs, we post data to the server, to a handler called ‘MailHandler.ashx’, the format used is JSON.

  6. Now, let’s write some C# Code :), to do this, add a new handler to your application, name it “MailHandler”, and paste this code below:
    public void ProcessRequest(HttpContext context)
            {
                string jsonString = String.Empty;
                HttpContext.Current.Request.InputStream.Position = 0;
                using (System.IO.StreamReader inputStream = 
                new System.IO.StreamReader(HttpContext.Current.Request.InputStream))
                {
                    jsonString = inputStream.ReadToEnd();
                    System.Web.Script.Serialization.JavaScriptSerializer jSerialize = 
                        new System.Web.Script.Serialization.JavaScriptSerializer();
                    var email = jSerialize.Deserialize<Mail>(jsonString);
    
                    if (email != null)
                    {
                        string from = email.From;
                        string to = email.To;
                        string body = email.Body;
                        //You can write here the code to send Email, 
                        //see ,the Class System.Net.Mail.MailMessage on MSDN
                        //Once the Mail is sent succefully, you can send back 
                        //a response to the Client informing him that everything is okay !
                        context.Response.Write(jSerialize.Serialize(
                             new
                             {
                                 Response = "Message Has been sent successfully"
                             }));
                    }
                }
            }

    As you can see here, we have used the method “ProcessRequest” to process the json request coming from the JavaScript client, we deserialize the request to get the data related to the Email (sender, receiver and the Body). In the end, we sent back a response to the Client informing him that everything is done okay.

    The client himself will receive the answer and will alert the user through the function mentioned below:

      function getSuccess(data, textStatus, jqXHR) {
    
    alert(data.Response);
    
    }

For all the Microsofties viewing my blog post, thank you for reading. Try to download the source code and do not hesitate to leave your questions and comments.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here