Below is a simple example of saving data from HTML text boxes to a SQL Server database using HTML + jQuery + ASP.NET Web API (C#).
Note: jQuery cannot connect directly to SQL Server. It sends data to a server-side API, and the API inserts the data into SQL Server.
1. SQL Server Table
CREATE TABLE Student
(
StudentID INT IDENTITY(1,1) PRIMARY KEY,
Name NVARCHAR(100),
Email NVARCHAR(100),
Mobile NVARCHAR(15)
);
2. HTML
<!DOCTYPE html>
<html>
<head>
<title>Save Data</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<h2>Student Registration</h2>
Name :
<input type="text" id="txtName"><br><br>
Email :
<input type="text" id="txtEmail"><br><br>
Mobile :
<input type="text" id="txtMobile"><br><br>
<input type="button" id="btnSave" value="Save">
<div id="msg"></div>
<script>
$("#btnSave").click(function () {
var student = {
Name: $("#txtName").val(),
Email: $("#txtEmail").val(),
Mobile: $("#txtMobile").val()
};
$.ajax({
url: "/api/student/save",
type: "POST",
contentType: "application/json",
data: JSON.stringify(student),
success: function (response) {
$("#msg").html("Record Saved Successfully.");
},
error: function () {
$("#msg").html("Error while saving record.");
}
});
});
</script>
</body>
</html>
3. C# Model
public class Student
{
public string Name { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
}
4. Web API Controller
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Http;
public class StudentController : ApiController
{
[HttpPost]
[Route("api/student/save")]
public IHttpActionResult Save(Student obj)
{
SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString);
SqlCommand cmd = new SqlCommand(
"INSERT INTO Student(Name,Email,Mobile) VALUES(@Name,@Email,@Mobile)", con);
cmd.Parameters.AddWithValue("@Name", obj.Name);
cmd.Parameters.AddWithValue("@Email", obj.Email);
cmd.Parameters.AddWithValue("@Mobile", obj.Mobile);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return Ok("Saved Successfully");
}
}
5. Web.config Connection String
<connectionStrings>
<add name="dbcon"
connectionString="Data Source=SERVERNAME;
Initial Catalog=CollegeDB;
Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
How It Works
HTML TextBox
│
▼
jQuery AJAX
│
▼
ASP.NET Web API
│
▼
SQL Server Database
Output
Suppose the user enters:
- Name: Nilesh Gupta
- Email: nilesh@gmail.com
- Mobile: 9876543210
After clicking Save, the following record is inserted into SQL Server:
| StudentID | Name | Mobile | |
|---|---|---|---|
| 1 | Nilesh Gupta | nilesh@gmail.com | 9876543210 |
No comments:
Post a Comment