In this article I will explain with an example, how to add new row to WebGrid using jQuery in ASP.Net MVC Razor.
The WebGrid will be populated from database using Entity Framework .
When the Add button is clicked, jQuery will add a new row to WebGrid and will also send the data to Controller’s Action method using AJAX and the record will be inserted to database Table using Entity Framework.
 
 
Database
I have made use of the following table Customers with the schema as follows.
Add new row to WebGrid using jQuery in ASP.Net MVC
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Note: For beginners in ASP.Net MVC and Entity Framework, please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework.
 
Add new row to WebGrid using jQuery in ASP.Net MVC
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, all the records from the Customers table is returned to the View as a Generic List collection.
If the database table does not contain any records, an empty object is inserted to the Generic List collection.
Note: The empty record is inserted because without any rows the WebGrid will not render on the page and thus it won’t be possible to access the WebGrid using jQuery.
 
Action method for handling jQuery AJAX operation
This Action method handles the call made from the jQuery AJAX function from the View.
Note: The following Action method handles AJAX calls and hence the return type is set to JsonResult.
 
Inside this Action method, the received Customer object is inserted into the Customers table and the updated Customer object with generated Customer Id is returned back to the View.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        CustomersEntities entities = new CustomersEntities();
        List<Customer> customers = entities.Customers.ToList();
 
        // If no records then add a dummy row.
        if (customers.Count == 0)
        {
            customers.Add(new Customer());
        }
 
        return View(customers);
    }
 
    [HttpPost]
    public JsonResult InsertCustomer(Customer customer)
    {
        using (CustomersEntities entities = new CustomersEntities())
        {
            entities.Customers.Add(customer);
            entities.SaveChanges();
            return Json(customer);
        }
    }
}
 
 
View
Inside the View, in the very first line the Customer Entity is declared as IEnumerable which specifies that the Model will be available as a Collection.
The WebGrid is initialized with the Model i.e. IEnumerable collection of Customer Entity class objects as source.
Note: For more information on usage of WebGrid, please refer WebGrid Step By Step Tutorial with example in ASP.Net MVC.
 
Below the WebGrid, two TextBoxes (Name and Country) and an Add Button has been placed. The Add Button has been assigned a jQuery click event handler.
 
Adding Rows to GridView using jQuery on Button Click
When the Add Button is clicked, the following jQuery click event handler is executed. Inside this event handler, first the WebGrid is referenced.
Note: The WebGrid is rendered as HTML Table in browser.
 
Then the first Row of the WebGrid is referenced in a jQuery variable and if its Cells are empty then the WebGrid Row is considered as dummy row and it is removed from the WebGrid.
The values of both the TextBoxes are fetched and are sent to the Controller’s Action method using jQuery AJAX function.
Once the response is received the values are assigned to the respective Cells of the Row and the Row is appended to the WebGrid.
@model IEnumerable<Customer>
 
@{
    Layout = null;
    WebGrid webGrid = new WebGrid(source: Model, canPage: true, canSort: false);
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
 
        .Grid {
            border: 1px solid #ccc;
            border-collapse: collapse;
        }
 
        .Grid th {
            background-color: #F7F7F7;
            font-weight: bold;
        }
 
        .Grid th, .Grid td {
            padding: 5px;
            width: 150px;
            border: 1px solid #ccc;
        }
 
        .Grid, .Grid table td {
            border: 0px solid #ccc;
        }
 
        .Grid th a, .Grid th a:visited {
            color: #333;
        }
    </style>
</head>
<body>
    @webGrid.GetHtml(
        htmlAttributes: new { @id = "WebGrid", @class = "Grid" },
        columns: webGrid.Columns(
                 webGrid.Column("Name", "Name"),
                 webGrid.Column("Country", "Country")))
    <br/>
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td style="width: 150px">
                Name:<br/>
                <input type="text" id="txtName" style="width:140px"/>
            </td>
            <td style="width: 150px">
                Country:<br/>
                <input type="text" id="txtCountry" style="width:140px"/>
            </td>
            <td style="width: 100px">
                <br/>
                <input type="button" id="btnAdd" value="Add"/>
            </td>
        </tr>
    </table>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnAdd").click(function () {
                //Reference the WebGrid.
                var webGrid = $("#WebGrid");
 
                //Reference the first row.
                var row = webGrid.find("tr").eq(1);
 
                //Check if row is dummy, if yes then remove.
                if ($.trim(row.find("td").eq(0).html()) == "") {
                    row.remove();
                }
 
                //Clone the reference first row.
                row = row.clone(true);
 
                //Reference the Name TextBox.
                var txtName = $("#txtName");
 
                //Reference the Country TextBox.
                var txtCountry = $("#txtCountry");
 
                //Send the records to server for saving to database.
                $.ajax({
                    type: "POST",
                    url: "/Home/InsertCustomer",
                    data: '{name: "' + txtName.val() + '", country: "' + txtCountry.val() + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        //Add the Name value to first cell.
                        SetValue(row, 0, txtName);
 
                        //Add the Country value to second cell.
                        SetValue(row, 1, txtCountry);
 
                        //Add the row to the WebGrid.
                        webGrid.append(row);
                    }
                });
 
            });
            function SetValue(row, index, textbox) {
                //Reference the Cell and set the value.
                row.find("td").eq(index).html(textbox.val());
 
                //Clear the TextBox.
                textbox.val("");
            }
        });
    </script>
</body>
</html>
 
 
Screenshot
Adding new to WebGrid using jQuery
Add new row to WebGrid using jQuery in ASP.Net MVC
 
Inserted records
Add new row to WebGrid using jQuery in ASP.Net MVC
 
 
Downloads