Hi Firuz,
Please go through the article carefully.specially Class Implementation section of it.you can create class after your aspx.cs class ends.
HTML
<div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=btnSave]").bind("click", function () {
var user = {};
user.Username = $("[id*=txtUsername]").val();
user.Password = $("[id*=txtPassword]").val();
$.ajax({
type: "POST",
url: "Default.aspx/SaveUser",
data: '{user: ' + JSON.stringify(user) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
return false;
});
});
</script>
</div>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
Username:
</td>
<td>
<asp:TextBox ID="txtUsername" runat="server" Text="" />
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSave" Text="Save" runat="server" />
</td>
</tr>
</table>
C#
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
[ScriptMethod]
public static void SaveUser(User user)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Users VALUES(@Username, @Password)"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Username", user.Username);
cmd.Parameters.AddWithValue("@Password", user.Password);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
public class User
{
public string Username { get; set; }
public string Password { get; set; }
}
I hope this will help you out.