In this article I will explain with an example, how to insert (save) data (records) to database using
Stored Procedure with
Entity Framework in ASP.Net.
Database
I have made use of the following table Customers with the schema as follow.
Note: You can download the database table SQL by clicking the download link below.
Stored Procedure for inserting data into Database
The following Stored Procedure will be used to insert data into the SQL Server database table.
CREATE PROCEDURE [dbo].[Insert_Customer]
@Name VARCHAR(100) = NULL
,@Country VARCHAR(100) = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE @CustomerId INT
INSERT INTO Customers(Name, Country)
VALUES(@Name, @Country)
SET @CustomerId = SCOPE_IDENTITY()
SELECT @CustomerId [CustomerId]
END
Entity Framework Model
Once the
Entity Framework is configured and connected to the database table, the Model will look as shown below.
Importing the Stored Procedure
Next step is to import the Stored Procedure by Right Clicking and selecting Update Model from Database option as shown below.
Then the Stored Procedure to be added needs to be selected and the Finish Button must be clicked.
Note: The above two steps are not required if the Stored Procedure has been added while creating the Entity Data Model.
Finally, in order to call the
Stored Procedure using
Entity Framework, the
Stored Procedure needs to be imported as a Function. Thus, again Right Click and select Add and then click on
Function Import option.
This will open the Add Function Import dialog window where the Function Name and the Stored Procedure to be imported as Function is selected.
Finally, the Scalar RadioButton is selected and the Int32 option is chosen from the DropDown.
HTML Markup
The HTML Markup Consists of following Controls:
TextBox – For capturing Name, Country to be inserted.
Button – For Add, Remove, Save the records.
The HTML Table consists of the following elements:
1. THEAD – The Header row.
2. TBODY – Left empty for dynamically adding (inserting) rows to the HTML Table.
3. TFOOT – The footer row, consisting of two TextBoxes and a Button for dynamically adding (inserting) rows to the HTML Table.
Populate HTML Table
Inside the
jQuery document ready event handler, a
jQuery AJAX is made to the
WebMethod i.e. GetCutomers.
Then inside the Success event handler, a loop is executed for each Customers return from the WebMethod.
Finally, the item of the HTML Table Row is cloned and the columns values are set to their respective fields.
Adding a new row
The
Add button in the Footer row of the HTML Table is assigned with a
jQuery clicked event handler.
Then inside the event handler value of the Name and Country are fetched from their respective TextBoxes and are added as a new row to the HTML Table.
Inserting multiple rows to database using AJAX
The
Save All button is assigned with a
jQuery clicked event handler.
Inside the event handler a loop is executed over all rows of the HTML Table Body and a JSON array of Customer objects is generated.
Then, the JSON array is then sent to the
WebMethod using
jQuery AJAX function and once the response is received it is displayed using
JavaScript Alert Message Box.
Removing a row
The
Remove button in any row of the HTML Table is assigned with a
jQuery clicked, then row and name is referenced.
Then check is performed and confirmation dialog box is displayed if user clicks on Ok button then, it gets the table reference and delete the row using its index.
<table id="tblCustomers">
<thead>
<tr>
<th>Name</th>
<th>Country</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td><asp:Button runat="server" Text="Remove" OnClientClick="return Remove(this)" /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
<td><asp:TextBox ID="txtCountry" runat="server"></asp:TextBox></td>
<td><asp:Button ID="btnAdd" runat="server" Text="Add" /></td>
</tr>
</tfoot>
</table>
<br />
<asp:Button ID="btnSave" runat="server" Text="Save All" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "CS.aspx/GetCustomers",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function (response) {
var row = $("#tblCustomers tbody tr:last-child").clone(true);
$("#tblCustomers tbody tr").not($("#tblCustomers tbody tr:first-child")).remove();
$.each(response.d, function (index, customer) {
$("td", row).eq(0).html(customer.Name);
$("td", row).eq(1).html(customer.Country);
$("#tblCustomers tbody").append(row);
row = $("#tblCustomers tbody tr:last-child").clone(true);
});
if ($("#tblCustomers tr").length > 2) {
$("#tblCustomers tr:eq(1)").remove();
}
},
error:function (response) {
alert(response.responseText);
}
});
$("[id*=btnAdd]" ).on("click", function () {
//Reference the Name and Country TextBoxes.
var txtName = $("[id*= txtName]");
var txtCountry = $("[id*= txtCountry]");
//Get the reference of the Table's TBODY element.
var tBody = $("#tblCustomers > TBODY")[0];
//Add Row.
var row = tBody.insertRow(-1);
//Add Name cell.
var cell = $(row.insertCell(-1));
cell.html(txtName.val());
//Add Country cell.
cell = $(row.insertCell(-1));
cell.html(txtCountry.val());
//Add Button cell.
cell = $(row.insertCell(-1));
var btnRemove = $("<input />");
btnRemove.attr("type", "button");
btnRemove.attr("onclick", "Remove(this);");
btnRemove.val("Remove");
cell.append(btnRemove);
//Clear the TextBoxes.
txtName.val("");
txtCountry.val("");
return false;
});
$("[id*= btnSave]" ).on("click", function () {
//Loop through the Table rows and build a JSON array.
var customers = new Array();
$("#tblCustomers TBODY TR").each(function () {
var row = $(this);
var customer = {};
customer.Name = row.find("TD").eq(0).html();
customer.Country = row.find("TD").eq(1).html();
customers.push(customer);
});
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "CS.aspx/InsertCustomers",
data: JSON.stringify({ customers: customers }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function (response) {
alert(response.d + " record(s) inserted.");
},
error:function (response) {
alert(response.responseText);
}
});
return false;
});
});
function Remove(button) {
//Determine the reference of the Row using the Button.
var row = $(button).closest("TR");
var name = $("TD", row).eq(0).html();
if (confirm("Do you want to delete: " + name)) {
//Get the reference of the Table.
var table = $("#tblCustomers")[0];
//Delete the Table row usingit's Index.
table.deleteRow(row[0].rowIndex);
}
return false;
};
</script>
WebMethod for populating the HTML Table
Inside the
WebMethod, records are fetched from
customers table and return using
Entity Framework.
C#
[WebMethod]
public static List<Customer>GetCustomers()
{
using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
{
List<Customer> customers = (from customer in entities.Customers
select customer).ToList();
return customers;
}
}
VB.Net
<WebMethod>
Public Shared Function GetCustomers() As List(Of Customer)
Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
Dim customers As List(Of Customer) = (From customer In entities.Customers
Select customer).ToList()
Return customers
End Using
End Function
WebMethod for inserting the records
The following WebMethod is executed when the AJAX call is made from the Save All Button is click.
Inside the truncate WebMethod, Generic List collection of Customer class object is received as parameter and all the records of the Customers table are deleted using the TRUNCATE command.
Then, a check is performed if Generic List collection of Customer class object is null then, new Generic List collection of Customer class object is created.
Now FOR EACH LOOP is executed over the customer using Generic List collection.
After that inserting each record into a SQL Server database via
Entity Framework while tracking the count of inserted records.
Finally, the Count of inserted record is returned back to the
jQuery AJAX function.
C#
[WebMethod]
public static int InsertCustomers(List<Customer> customers)
{
using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
{
//Truncate Table to delete all old records.
entities.Database.ExecuteSqlCommand("TRUNCATE TABLE [Customers]");
//Check for NULL.
if (customers == null)
{
customers = new List<Customer>();
}
//Loop and insert records.
int insertedRecords = 0;
foreach (Customer customer in customers)
{
entities.InsertCustomer(customer.Name,customer.Country);
insertedRecords++;
}
return insertedRecords;
}
}
VB.Net
<WebMethod>
Public Shared Function InsertCustomers(customers As List(Of Customer)) As Integer
Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
'Truncate Table to delete all old records.
entities.Database.ExecuteSqlCommand("TRUNCATE TABLE [Customers]")
'Check for NULL.
If customers Is Nothing Then
customers = New List(Of Customer)()
End If
'Loop and insert records.
Dim insertedRecords As Integer = 0
For Each customer As Customer In customers
entities.InsertCustomer(customer.Name,customer.Country)
insertedRecords += 1
Next
Return insertedRecords
End Using
End Function
Screenshot
Downloads