ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method

This simple tutorial explains how to CRUD (Create, Retrieve, Update, and Delete) Records from two one-to-many linked tables (Category and Product) and display in a web grid. Data can be searched with multiple search facility, search by id or search by part of name. The Models are created using Entity Framework Database Method.

Software Required

  1. Visual Studio 2013 or above
  2. Entity Framework 6.0 (Available with Visual Studio)
  3. .NET Framework 4.5 or above (Available with Visual Studio)
  4. SQL Server Database (Available with Visual Studio)

Start Visual Studio and create a new MVC Project as displayed below.

Go to File >> New >> Project. Name the project as ShoppingCart.

 ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method
 
ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method 

Choose project type as MVC, as shown below.

ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method 

The project is created and opens.

ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method 

Creating Database File Store.mdf

Right-click on App_Data folder and got to Add >> New Item >> SQL Server Database.

Name it as Store.mdf as displayed below. The Server Explorer window opens. Create two tables "Category" and "Product" and populate them by executing the provided queries below.

ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method
 
ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method 

Store .mdf Database File is created as shown below. Right click on Store.mdf file - Open

ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method
 
ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method 
  1. CREATE TABLE [dbo].[Category] (  
  2.     [CategoryId]   INT           NOT NULL,  
  3.     [CategoryName] NVARCHAR (30) NOT NULL,  
  4.     [Remark]       NVARCHAR (50) NOT NULL,  
  5.     PRIMARY KEY CLUSTERED ([CategoryId] ASC)  
  6. );  
  7.   
  8. INSERT INTO [dbo].[Category] ([CategoryId], [CategoryName], [Remark]) VALUES (1, N'Computer', N'Desktop & Laptopd')  
  9. INSERT INTO [dbo].[Category] ([CategoryId], [CategoryName], [Remark]) VALUES (2, N'Storage', N'Pendrive & HardDisk')  
  10. INSERT INTO [dbo].[Category] ([CategoryId], [CategoryName], [Remark]) VALUES (3, N'Acssories', N'Mouse etc')  
  11. INSERT INTO [dbo].[Category] ([CategoryId], [CategoryName], [Remark]) VALUES (4, N'Digital Camera', N'Digital Camera')  
  12. INSERT INTO [dbo].[Category] ([CategoryId], [CategoryName], [Remark]) VALUES (5, N'Camera Aceesories', N'Camera Acessories')  
  13.   
  14. CREATE TABLE [dbo].[Product] (  
  15.     [ProductId]    INT           NOT NULL,  
  16.     [ProductName]  NVARCHAR (30) NOT NULL,  
  17.     [Price]        DECIMAL (18)  NOT NULL,  
  18.     [ReorderLevel] INT           NOT NULL,  
  19.     [CatId]        INT           NOT NULL,  
  20.     PRIMARY KEY CLUSTERED ([ProductId] ASC),  
  21.     CONSTRAINT [fk_cat_product_id] FOREIGN KEY ([CatId]) REFERENCES [dbo].[Category] ([CategoryId]) ON DELETE CASCADE  
  22. );  
  23.   
  24. INSERT INTO [dbo].[Product] ([ProductId], [ProductName], [Price], [ReorderLevel], [CatId]) VALUES (1, N'Lenovo5000'CAST(25500 AS Decimal(18, 0)), 24, 1)  
  25. INSERT INTO [dbo].[Product] ([ProductId], [ProductName], [Price], [ReorderLevel], [CatId]) VALUES (2, N'SanDisk Penrive'CAST(250 AS Decimal(18, 0)), 300, 2)  
  26. INSERT INTO [dbo].[Product] ([ProductId], [ProductName], [Price], [ReorderLevel], [CatId]) VALUES (3, N'sonyharddisk'CAST(3000 AS Decimal(18, 0)), 31, 2)  
  27. INSERT INTO [dbo].[Product] ([ProductId], [ProductName], [Price], [ReorderLevel], [CatId]) VALUES (4, N'Sony Mouse'CAST(350 AS Decimal(18, 0)), 21, 3)  
  28. INSERT INTO [dbo].[Product] ([ProductId], [ProductName], [Price], [ReorderLevel], [CatId]) VALUES (5, N'Sony PenDrive 16GB'CAST(470 AS Decimal(18, 0)), 45, 2)  
  29. INSERT INTO [dbo].[Product] ([ProductId], [ProductName], [Price], [ReorderLevel], [CatId]) VALUES (6, N'Zebronics Mouse'CAST(300 AS Decimal(18, 0)), 54, 3)  
  30. INSERT INTO [dbo].[Product] ([ProductId], [ProductName], [Price], [ReorderLevel], [CatId]) VALUES (7, N'Sony Camera Stand'CAST(2500 AS Decimal(18, 0)), 22, 5)  
  31. INSERT INTO [dbo].[Product] ([ProductId], [ProductName], [Price], [ReorderLevel], [CatId]) VALUES (8, N'Sony Camera Lens'CAST(65000 AS Decimal(18, 0)), 12, 5)  
  32. INSERT INTO [dbo].[Product] ([ProductId], [ProductName], [Price], [ReorderLevel], [CatId]) VALUES (9, N'Canon Camera Lens'CAST(30000 AS Decimal(18, 0)), 20, 5)  

Right-click on Tables >> New Query.

ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method 

Copy and paste the SQL query for creating the Category table as above and execute it by clicking the arrow symbol on the left. The Category table would be created.

Insert the records by executing the INSERT query as displayed below.

ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method 

Similarly, create the Product table and insert Product records.

Refresh the Tables folder in the Server Explorer window. The newly created 2 tables will be seen.

ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method 

Entity Framework database models will be created by the Database-First method.

 Please click here to go to my article describing how to create models from database tables using the Database-First method.

Code for the CategoryModel Class is given below.

  1. namespace ShoppingCart.Models  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.       
  6.     public partial class Category  
  7.     {  
  8.         [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage""CA2214:DoNotCallOverridableMethodsInConstructors")]  
  9.         public Category()  
  10.         {  
  11.             this.Products = new HashSet<Product>();  
  12.         }  
  13.       
  14.         public int CategoryId { getset; }  
  15.         public string CategoryName { getset; }  
  16.         public string Remark { getset; }  
  17.       
  18.         [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage""CA2227:CollectionPropertiesShouldBeReadOnly")]  
  19.         public virtual ICollection<Product> Products { getset; }  
  20.     }  
  21. }  

Code for the Product Model class is mentioned below.

  1. namespace ShoppingCart.Models  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.       
  6.     public partial class Product  
  7.     {  
  8.         public int ProductId { getset; }  
  9.         public string ProductName { getset; }  
  10.         public decimal Price { getset; }  
  11.         public int ReorderLevel { getset; }  
  12.         public int CatId { getset; }  
  13.       
  14.         public virtual Category Category { getset; }  
  15.     }  
  16. }  

Creating View Model Class (ProductWithCategoryVM)

This class will be created by combining the properties from Category class and Product class respectively. It will be used in the Controller and to create View also.

Right-click on the Models folder and click Add >> Class.

Name it as ProductWithCategoryVM.

ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method 

Code for the ProductWithCategory View Model Class is as below.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.ComponentModel.DataAnnotations;  
  6.   
  7. namespace ShoppingCart.Models  
  8. {  
  9.     public class ProductWithCategoryVM  
  10.     {  
  11.         public int ProductId { getset; }  
  12.         public string ProductName { getset; }  
  13.         public decimal Price { getset; }  
  14.         public int ReorderLevel { getset; }  
  15.         public string CategoryName { getset; }  
  16.         public Product Product { getset; }  
  17.     }  
  18. }  

Code for the Home Controller class is given below.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Data;  
  7. using System.Data.Entity;  
  8. using System.Net;  
  9. using ShoppingCart.Models;  
  10.   
  11. namespace ShoppingCart.Controllers  
  12. {  
  13.     public class HomeController : Controller  
  14.     {  
  15.         DBContext db = new DBContext();  
  16.   
  17.         public ActionResult Products(string q, string S)  
  18.         {  
  19.             //Populating Department DropDownList in View  
  20.             ViewBag.Categories = new SelectList(db.Categories, "CategoryId""CategoryName");  
  21.   
  22.   
  23.             //Searching Record  
  24.             int id = Convert.ToInt32(Request["SearchType"]);  
  25.             var searchParameter = "Searching";  
  26.             var ProductWithCategoryVMlist = (from P in db.Products  
  27.                                              join C in db.Categories on  
  28.               P.CatId equals C.CategoryId  
  29.   
  30.                                              select new ProductWithCategoryVM  
  31.                                              {  
  32.                                                  ProductId = P.ProductId,  
  33.                                                  ProductName = P.ProductName,  
  34.                                                  Price = P.Price,  
  35.                                                  ReorderLevel = P.ReorderLevel,  
  36.                                                  CategoryName = P.Category.CategoryName  
  37.                                              });  
  38.             if (!string.IsNullOrWhiteSpace(q))  
  39.             {  
  40.                 switch (id)  
  41.                 {  
  42.                     case 0:  
  43.                         int iQ = int.Parse(q);  
  44.                         ProductWithCategoryVMlist = ProductWithCategoryVMlist.Where(p => p.ProductId.Equals(iQ));  
  45.                         searchParameter += " ProductId for ' " + q + " '";  
  46.                         break;  
  47.                     case 1:  
  48.                         ProductWithCategoryVMlist = ProductWithCategoryVMlist.Where(p => p.ProductName.Contains(q));  
  49.                         searchParameter += " Product Name for ' " + q + " '";  
  50.                         break;  
  51.                     case 2:  
  52.                         ProductWithCategoryVMlist = ProductWithCategoryVMlist.Where(p => p.CategoryName.Contains(q));  
  53.                         searchParameter += " Category Name for '" + q + "'";  
  54.                         break;  
  55.                 }  
  56.             }  
  57.             else  
  58.             {  
  59.                 searchParameter += "ALL";  
  60.             }  
  61.   
  62.             ViewBag.SearchParameter = searchParameter;  
  63.             return View(ProductWithCategoryVMlist.ToList()); //List of Products with Category Name)  
  64.             //return View(ProductWithCategoryVMlist); //List of Products with Category Name)  
  65.         }  
  66.   
  67.         public ActionResult About()  
  68.         {  
  69.             ViewBag.Message = "Your application description page.";  
  70.   
  71.             return View();  
  72.         }  
  73.         [HttpPost]  
  74.         public ActionResult Insert()  
  75.         {  
  76.   
  77.             try  
  78.             {  
  79.                 string ProductName = Request["txtPName"].ToString();  
  80.                 int CatId = Convert.ToInt32(Request["Categories"].ToString());  
  81.                 decimal price = Convert.ToDecimal(Request["txtPrice"].ToString());  
  82.                 int ReorderLevel = Convert.ToInt32(Request["txtReorderLevel"].ToString());  
  83.                 int NextId = db.Products.Max(p => (int)p.ProductId) + 1;  
  84.                 Product NewProduct = new Product();  
  85.                 NewProduct.ProductId = NextId;  
  86.                 NewProduct.ProductName = ProductName;  
  87.                 NewProduct.CatId = CatId;  
  88.                 NewProduct.Price = price;  
  89.                 NewProduct.ReorderLevel = ReorderLevel;  
  90.                 db.Products.Add(NewProduct);  
  91.                 db.SaveChanges();  
  92.                 //Sending Data To Products Controller.  
  93.                 TempData["Message"] = "Record saved successfully";  
  94.             }  
  95.             catch  
  96.             {  
  97.                 TempData["Message"] = "Error while saving record";  
  98.             }  
  99.             return RedirectToAction("Products");  
  100.   
  101.         }  
  102.         // GET: /Product/Edit/5  
  103.         public ActionResult Edit(int? id)  
  104.         {  
  105.             if (id == null)  
  106.             {  
  107.                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  108.             }  
  109.             Product editProduct = db.Products.Find(id);  
  110.             //ViewBag.CategoryListItems = db.Categories.Distinct().Select(i => new SelectListItem() { Text = i.CategoryName, Value = i.CategoryId.ToString() }).ToList();  
  111.             //Populating Department DropDownList in View  
  112.             ViewBag.Categories = new SelectList(db.Categories, "CategoryId""CategoryName");  
  113.             if (editProduct == null)  
  114.             {  
  115.                 return HttpNotFound();  
  116.             }  
  117.             return View(editProduct);  
  118.         }  
  119.   
  120.         // POST: /Product/Edit/5  
  121.         // To protect from overposting attacks, please enable the specific properties you want to bind to, for   
  122.         // more details see http://go.microsoft.com/fwlink/?LinkId=317598.  
  123.         [HttpPost]  
  124.         [ValidateAntiForgeryToken]  
  125.         public ActionResult Edit([Bind(Include = "ProductId,ProductName,CatId,Price,ReorderLevel")] Product editProduct)  
  126.         {  
  127.             try  
  128.             {  
  129.                 if (ModelState.IsValid)  
  130.                 {  
  131.                     int CatId = Convert.ToInt32(Request["Categories"].ToString());  
  132.                     editProduct.CatId = CatId;  
  133.                     db.Entry(editProduct).State = EntityState.Modified;  
  134.                     db.SaveChanges();  
  135.                     editProduct = null;  
  136.                     TempData["Message"] = "Record updated successfully";  
  137.                     return RedirectToAction("Products");  
  138.                 }  
  139.             }  
  140.             catch  
  141.             {  
  142.                 TempData["Message"] = "Error while updating record";  
  143.             }  
  144.             return RedirectToAction("Products");  
  145.   
  146.         }  
  147.         // GET: /Product/Delete/5  
  148.         public ActionResult Delete(int? id)  
  149.         {  
  150.             if (id == null)  
  151.             {  
  152.                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  153.             }  
  154.             Product deleteProduct = db.Products.Find(id);  
  155.             if (deleteProduct == null)  
  156.             {  
  157.                 return HttpNotFound();  
  158.             }  
  159.             return View(deleteProduct);  
  160.         }  
  161.   
  162.         // POST: /Product/Delete/5  
  163.         [HttpPost, ActionName("Delete")]  
  164.         [ValidateAntiForgeryToken]  
  165.         public ActionResult DeleteConfirmed(int id)  
  166.         {  
  167.             try  
  168.             {  
  169.                 Product deleteProduct = db.Products.Find(id);  
  170.                 db.Products.Remove(deleteProduct);  
  171.                 db.SaveChanges();  
  172.                 deleteProduct = null;  
  173.                 TempData["Message"] = "Record Deleted successfully";  
  174.                 return RedirectToAction("Products");  
  175.                   
  176.             }  
  177.             catch  
  178.             {  
  179.                 TempData["Message"] = "Error while deleting record";  
  180.             }  
  181.             return RedirectToAction("Products");  
  182.         }  
  183.   
  184.   
  185.           
  186.         public ActionResult Contact()  
  187.         {  
  188.             ViewBag.Message = "Your contact page.";  
  189.   
  190.             return View();  
  191.         }  
  192.     }  
  193. }  

This is the code for the View Products.cshtml page.

  1. @model List<ShoppingCart.Models.ProductWithCategoryVM>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Product List";  
  5.     Layout = null;     
  6.   
  7. }  
  8.   
  9. <!DOCTYPE html>  
  10.   
  11. <html>  
  12. <head>  
  13.     <meta name="viewport" content="width=device-width" />  
  14.     <title>Index</title>  
  15.     <style type="text/css">  
  16.         .webGrid {  
  17.             margin: 4px;  
  18.             border-collapse: collapse;  
  19.             width: 700px;  
  20.             font-family: Tahoma;  
  21.             font-size: small;  
  22.         }  
  23.   
  24.         .grid-header {  
  25.             background-color: #990000;  
  26.             font-weight: bold;  
  27.             color: White !important;  
  28.         }  
  29.   
  30.         .webGrid th a {  
  31.             color: White;  
  32.             text-decoration: none;  
  33.         }  
  34.   
  35.         .webGrid th, .webGrid td {  
  36.             border: 1px solid black;  
  37.             padding: 5px;  
  38.         }  
  39.   
  40.         .alt {  
  41.             background-color: #F4EFEF;  
  42.         }  
  43.   
  44.         .webGrid th a:hover {  
  45.             text-decoration: underline;  
  46.         }  
  47.   
  48.         .to-the-right {  
  49.             text-align: right;  
  50.         }  
  51.     </style>  
  52. </head>  
  53. <body>  
  54.   
  55.     <center>  
  56.   
  57.         <h2>Custom Search for Product</h2>  
  58.         @using (Html.BeginForm("Products", "Home", FormMethod.Get, new { @class = "Search-form" }))  
  59.         {  
  60.             <div id="txtBox">  
  61.                 @Html.Label("Search Products ")  
  62.                 <input type="text" name="q" />  
  63.             </div>  
  64.             <div id="radioList">  
  65.                 @Html.RadioButton("SearchType", "0")  
  66.                 @Html.Label("ID")  
  67.                 @Html.RadioButton("SearchType", "1", true)  
  68.                 @Html.Label("Product Name")  
  69.                 @Html.RadioButton("SearchType", "2")  
  70.                 @Html.Label("Category Name")  
  71.             </div>  
  72.             <div id="btnSearch">  
  73.                 <input type="submit" value="Search" id="btnSubmit"  />  
  74.             </div>  
  75.         }  
  76.         <br />  
  77.         <div id="DivGrid">  
  78.             @{  
  79.                            var grid = new WebGrid(source: Model, canPage: true, rowsPerPage: 2, defaultSort: "ProductId");  
  80.                            if (Model.Count() > 0)  
  81.                      {  
  82.                                       <div><strong> @ViewBag.SearchParameter</strong> | @grid.TotalRowCount @Html.Label("Record(s) found")</div>  
  83.                                     @grid.GetHtml(  
  84.         tableStyle: "webGrid",  
  85.         headerStyle: "grid-header",  
  86.         rowStyle: "gridRow",  
  87.         alternatingRowStyle: "alt",  
  88.         mode: WebGridPagerModes.All,  
  89.         firstText: "<< First",  
  90.         previousText: " < Previous",  
  91.         nextText: "Next >",  
  92.         lastText: "Last >>",  
  93.         caption: "Products",  
  94.          columns: grid.Columns(  
  95.   
  96.                                             grid.Column("ProductId", "Product Id"),  
  97.                                             grid.Column("ProductName", "Product Name"),  
  98.                                             grid.Column("Price", "Price"),  
  99.                                             grid.Column("ReorderLevel", "Reorder Level"),  
  100.                                             grid.Column("CategoryName", "Category"),  
  101.                                             grid.Column(header: "Action", format: (item) =>  
  102.                                                {  
  103.                                                    var link = Html.ActionLink("Edit", "Edit", new { id = item.ProductId });  
  104.                                                    return link;  
  105.                                                }),  
  106.   
  107.                                              grid.Column(header: "Action", format: (item) =>  
  108.                                                {  
  109.                                                     var link = Html.ActionLink("Delete", "Delete", new { id = item.ProductId });  
  110.                                                     return link;  
  111.                                                }),  
  112.                                              grid.Column(header: "Action", format: @<text>@Html.ActionLink("Detail", null, null, new { @onclick = "return GetSelectedRow(this);" })</text>)  
  113.                                                ))  
  114.                                     <script type="text/javascript">  
  115.                                         function GetSelectedRow(link) {  
  116.                                             var row = link.parentNode.parentNode;  
  117.                                             var message = "Selected Product Detail";  
  118.                                             message += "\n\n Product Id: " + row.getElementsByTagName("TD")[0].innerHTML;  
  119.                                             message += "\n Product Name: " + row.getElementsByTagName("TD")[1].innerHTML;  
  120.                                             message += "\n Price: " + row.getElementsByTagName("TD")[2].innerHTML;  
  121.                                             message += "\n ReorderLevel: " + row.getElementsByTagName("TD")[3].innerHTML;  
  122.                                             message += "\n Category Name: " + row.getElementsByTagName("TD")[4].innerHTML;  
  123.                                             alert(message);  
  124.                                             return false;  
  125.                                         }  
  126.   
  127.                                     </script>  
  128.   
  129.           
  130.     }  
  131.     else  
  132.     {  
  133.                     <hr />@Html.Label("No, Record(s) not found")<hr />  
  134.                 }  
  135.             }  
  136.   
  137.         </div>  
  138. </center>  
  139.     <div>        
  140.            @using (Html.BeginForm("Insert", "Home", FormMethod.Post))  
  141.            {  
  142.             <center>  
  143.                 <table cellpadding="0" cellspacing="0">  
  144.                     <tr>  
  145.                         <th colspan="2" align="center">Add Product</th>  
  146.                     </tr>  
  147.   
  148.                     <tr>  
  149.   
  150.                         <td>@Html.Label("Enter Product Name:") </td>  
  151.                         <td>@Html.TextBox("txtPName")</td>  
  152.   
  153.                     </tr>  
  154.                     <tr>  
  155.                         <td>@Html.Label("Select Category Type:")</td>  
  156.   
  157.                         <td>  
  158.                             @Html.DropDownList("Categories", (IEnumerable<SelectListItem>)ViewBag.Categories, "Select Category")  
  159.                         </td>  
  160.   
  161.                     </tr>  
  162.   
  163.                     <tr>  
  164.                         <td>@Html.Label("Enter Product Price:")</td>  
  165.                         <td>@Html.TextBox("txtPrice")</td>  
  166.                     </tr>  
  167.                     <tr>  
  168.   
  169.                         <td>@Html.Label("Enter  ReorderLevel:")</td>  
  170.   
  171.                         <td>@Html.TextBox("txtReorderLevel")</td>  
  172.                     </tr>  
  173.                     <tr >  
  174.                         <td></td>  
  175.                         <td style="text-align: center"><input type="submit" value="Submit" /></td>  
  176.                     </tr>  
  177.                     <tr  ><td style="text-align: center;color:Red"><div style="color: Red">@ViewBag.Message</div></td></tr>  
  178.                 </table>  
  179.             </center>  
  180.            }  
  181.   
  182. </div>  
  183.    @if (@TempData["Message"] != null)  
  184.    {  
  185.     <script type="text/javascript">  
  186.         window.onload = function () {  
  187.             alert("@TempData["Message"]");  
  188.         };  
  189.     </script>  
  190.    }  
  191. </body>  
  192. </html> 

Create two new Views by right clicking the Home folder under Views folder - View.Name then Edit and Delete. Modify them as given below.

Edit View (Edit.cshtml)

  1. @model ShoppingCart.Models.Product  
  2. @{  
  3.     ViewBag.Title = "Edit";  
  4. }  
  5. <title>Edit</title>  
  6. @using (Html.BeginForm("Edit", "Home", FormMethod.Post))  
  7. {  
  8.     @Html.AntiForgeryToken()  
  9.     <div>  
  10.         <h3 style="color:forestgreen;text-align:center;width:500px">Edit</h3>   
  11.         <table width="500px" cellpadding="5" cellspacing="5" border="1" style="border: 1 solid black;  
  12.             border-collapse: collapse;">  
  13.             <tr>  
  14.                 <td colspan="2" align="center">Product</td>  
  15.             <tr>  
  16.                 <td align="right">  
  17.                     Product Id :  
  18.                 </td>  
  19.                 <td align="left">  
  20.                     @Html.DisplayFor(model => model.ProductId)  
  21.                     @Html.Hidden("Id", Model.ProductId)  
  22.                 </td>  
  23.             </tr>  
  24.             <tr>  
  25.                 <td align="right">  
  26.                     Product Name :  
  27.                 </td>  
  28.                 <td align="left">  
  29.                 @Html.EditorFor(model => model.ProductName, new { htmlAttributes = new { @class = "form-control" } })  
  30.                 @Html.ValidationMessageFor(model => model.ProductName, "", new { @class = "text-danger" })  
  31.                 @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
  32.                 @*@Html.Hidden("Id", Model.ProductId)*@  
  33.                @Html.HiddenFor(model => model.ProductId)  
  34.             </td>  
  35.         </tr>  
  36.         <tr>  
  37.             <td align="right">  
  38.                 Price :  
  39.             </td>  
  40.             <td align="left">  
  41.                 @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })  
  42.                 @Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-                       danger" })  
  43.             </td>  
  44.         </tr>  
  45.         <tr>  
  46.             <td align="right">  
  47.                 Reorder Level:  
  48.             </td>  
  49.             <td align="left">  
  50.                 @Html.EditorFor(model => model.ReorderLevel, new { htmlAttributes = new { @class = "form-control" } })  
  51.                 @Html.ValidationMessageFor(model => model.ReorderLevel, "", new { @class = "text-danger" })  
  52.             </td>  
  53.         </tr>  
  54.         <tr>  
  55.             <td align="right">  
  56.                 Category :  
  57.             </td>  
  58.             <td align="left">  
  59.                 @Html.DropDownList("Categories", (IEnumerable<SelectListItem>)ViewBag.Categories, "Select Category")  
  60.             @Html.ValidationMessageFor(model => model.CatId, "", new { @class = "text- danger" })  
  61.         </td>  
  62.     </tr>  
  63.   
  64. </table>  
  65. <div style="text-align:center;width:500px" class="form-actions no-color">  
  66.     <input type="submit" value="Update" class="btn btn-primary" />  
  67.      |  
  68.     @Html.ActionLink("Back", "Products", "Home", new { @class = "btn btn-primary" })  
  69.     @*@Html.ActionLink("Back to List", "Products")*@  
  70.   
  71. </div>  
  72. </div>  
  73. }  

Delete View (Delete.cshtml)

  1. @model ShoppingCart.Models.Product  
  2. @{  
  3.     ViewBag.Title = "Delete";  
  4. }  
  5.                     <title>Delete</title>  
  6. @using (Html.BeginForm("Delete", "Home", FormMethod.Post))  
  7.      
  8.     {  
  9.     <div>  
  10.         <h3 style="color:forestgreen;text-align:center;width:500px">Delete</h3>          
  11.         <h4 style="color:red">Are you sure you want to delete this?Record once deleted can not be retrieved.</h4>  
  12.                         
  13.         <table width="500px" cellpadding="5"  cellspacing="5" border="1" style="border:  solid black;  
  14.             border-collapse: collapse;">  
  15.             <tr>  
  16.                 <td colspan="2" align="center">Product</td>  
  17.             </tr>  
  18.             <tr>  
  19.                 <td align="right">  
  20.                     Product Id :  
  21.                 </td>  
  22.                 <td align="left">  
  23.                     @Html.DisplayFor(model => model.ProductId)  
  24.                     @Html.Hidden("Id", Model.ProductId)  
  25.                 </td>  
  26.             </tr>  
  27.             <tr>  
  28.                 <td align="right">  
  29.                     Product Name :  
  30.                 </td>  
  31.                 <td align="left">  
  32.                     @Html.DisplayFor(model => model.ProductName)  
  33.                 @Html.Hidden("Id", Model.ProductId)  
  34.             </td>  
  35.         </tr>  
  36.         <tr>  
  37.             <td align="right">  
  38.                 Price :  
  39.             </td>  
  40.             <td align="left">  
  41.                 @Html.DisplayFor(model => model.Price)  
  42.         </td>  
  43.     </tr>  
  44.     <tr>  
  45.         <td align="right">  
  46.             Reorder Level:  
  47.         </td>  
  48.         <td align="left">  
  49.             @Html.DisplayFor(model => model.ReorderLevel)  
  50.     </td>  
  51. </tr>  
  52. <tr>  
  53.     <td align="right">  
  54.         Category :  
  55.     </td>  
  56.     <td align="left">  
  57.         @Html.DisplayFor(model => model.Category.CategoryName)  
  58. </td>  
  59. </tr>  
  60.             
  61.               
  62.     </table>  
  63.         @using (Html.BeginForm())  
  64.         {  
  65.             @Html.AntiForgeryToken()  
  66.   
  67.             <div  style="text-align:center;width:500px"  class="form-actions no-color">  
  68.             <input type="submit" value="Delete" class="btn btn-primary" /> |  
  69.                 @*@Html.ActionLink("Back to List", "Products")*@  
  70.                @Html.ActionLink("Back", "Products", "Home", new { @class = "btn btn-primary" })  
  71.             </div>  
  72.         }  
  73. </div>  
  74.    }  

Connection String in Web.Config file is as given below.

  1. <connectionStrings>  
  2.     <add name="DBContext" connectionString="metadata=res://*/Models.StoreModel.csdl|res://*/Models.StoreModel.ssdl|res://*/Models.StoreModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\Store.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  
  3.   </connectionStrings>  

Run the project. The page below is displayed, which contains web grid with data and search by id and name functionality. Add a record functionality there also:

ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method 

Insert Record

ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method 

Update Record

ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method 

Delete Record

ASP.NET MVC WebGrid With CRUD Record From Two Tables And Custom Search Functionality Using Entity Framework Database First Method


Similar Articles