Click here to Skip to main content
15,881,709 members
Articles / Web Development / HTML
Tip/Trick

How to send Data from JavaScript to C# Server Code

Rate me:
Please Sign up or sign in to vote.
4.57/5 (6 votes)
24 Oct 2014CPOL2 min read 70.2K   1.2K   22   4
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.
    HTML
      <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:
    JavaScript
    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:
    C#
    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:

    JavaScript
      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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
France France
Sofiene Rabhi is Microsoft certified professional in C# ,HTML 5 and JavaScript, Asp.net and Microsoft Silverlight, consultant, trainer specializing in application development with Microsoft technologies, including c#, Vb.net, and Microsoft Azure.

Comments and Discussions

 
QuestionExample Pin
Bilal Qureshi31-Aug-15 2:43
Bilal Qureshi31-Aug-15 2:43 
Questionadd jquery from cdn Pin
imransaharp27-Oct-14 2:29
imransaharp27-Oct-14 2:29 
XML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

AnswerRe: add jquery from cdn Pin
Soufiane Rabhi 27-Oct-14 12:38
Soufiane Rabhi 27-Oct-14 12:38 
GeneralMy vote of 4 Pin
majid torfi26-Oct-14 5:09
professionalmajid torfi26-Oct-14 5:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.