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
- Open Visual Studio (This blog post was done by VS 2013.)
- Choose C# => Web => ASP.NET Web Application => Empty
- Visual Studio 2013 will generate an empty ASP.NET project for you.
- 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.
- 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.
- 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;
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.