In this article, I am explaining how to use Razor View in ASP.NET MVC with the Entity Framework. You learn how to use the Entity Wizard to create an ADO.NET Entity Data Model. I also illustrate how to select, insert, update, and delete database data by using the Entity Framework.
In order to use the Entity Framework, you need to create an Entity Data Model. For adding Entity Model:
1) Right click on Model Folder in the solution explorer.
2) Select Add Ă New Item.
Select ADO.NET Entity Data Model from Add New Item template. You can change the name of Data Model with .edmx extension. Here I change it into ProductDb.edmx.
Then Select Generate from Database option and Click on Next button.
Here you have to provide the connection string properties in a dialog box:
1) Provide your server name.
2) If you are using Windows mode do not provide Username and password else
provide both of them in the case of SQL Server Authentication.
3) Select the database from the available list.
After establishing a new connection or selecting a database click on Next button to proceed.
Here I change name of entity connection setting as ProductDetails in Web.config.
Then select the table from the table list in the database as shown below. Here I am selection a product table for my application. After selecting a table clicks on Finish button.
The structures of my Product table in the database are as:
create table Product
(
product_id int identity primary key,
product_category varchar(20),
product_name varchar(20),
product_quantity int,
product_price int
)
After adding an entity model to have to add the Views in which you can select, update, insert or delete database records.
First add Index View that displays the list of product from the database. For adding View right click on Controller Index Action Ă Select Add View.
When you select an Add View option, a dialog box will open. Select entity model class as our strongly typed view and List from Scaffold template.
You can modify a view (Index View) as I had modified below:
@model IEnumerable<RazrMVCApp.Models.Product>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<style type="text/css">
div
{
font-family:Calibri;
}
</style>
</head>
<body>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table align="center" cellpadding="10" border="1px">
<tr style="background-color:Aqua">
<th></th>
<th>Product ID</th>
<th>Product Category</th>
<th>Product Name</th>
<th>Product Quantity</th>
<th>Product Price</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.product_id }) |
@Html.ActionLink("Details", "Details", new { id=item.product_id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.product_id })
</td>
<td>@item.product_id</td>
<td>@item.product_category</td>
<td>@item.product_name</td>
<td>@item.product_quantity</td>
<td>@item.product_price</td>
</tr>
}
</table>
</body>
</html>
Then add Edit View and this time select Edit option from Scaffold template list:
Edit View:
@model RazrMVCApp.Models.Product
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Edit</title>
<style type="text/css">
div
{
font-family:Calibri;
}
</style>
</head>
<body>
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Product</legend>
@Html.HiddenFor(model => model.product_id)
<div class="editor-label">
@Html.LabelFor(model => model.product_category)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.product_category)
@Html.ValidationMessageFor(model => model.product_category)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.product_name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.product_name)
@Html.ValidationMessageFor(model => model.product_name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.product_quantity)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.product_quantity)
@Html.ValidationMessageFor(model => model.product_quantity)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.product_price)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.product_price)
@Html.ValidationMessageFor(model => model.product_price)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div> @Html.ActionLink("Back to List", "Index")</div>
</body>
</html>
Add Details View and select Details option from Scaffold template list:
Details View:
@model RazrMVCApp.Models.Product
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Details</title>
<style type="text/css">
div
{
font-family:Calibri;
}
</style>
</head>
<body>
<fieldset>
<legend>Product</legend>
<div class="display-label">Product Category</div>
<div class="display-field">@Model.product_category</div>
<div class="display-label">Product Name</div>
<div class="display-field">@Model.product_name</div>
<div class="display-label">Product Quantity</div>
<div class="display-field">@Model.product_quantity</div>
<div class="display-label">Product Price</div>
<div class="display-field">@Model.product_price</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { id=Model.product_id }) |
@Html.ActionLink("Back to List", "Index")
</p>
</body>
</html>
Add Delete View and select Delete option from Scaffold template list:
Delete View:
@model RazrMVCApp.Models.Product
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Delete</title>
<style type="text/css">
div
{
font-family:Calibri;
}
</style>
</head>
<body>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>Product</legend>
<div class="display-label">Product Category</div>
<div class="display-field">@Model.product_category</div>
<div class="display-label">Product Name</div>
<div class="display-field">@Model.product_name</div>
<div class="display-label">Product Quantity</div>
<div class="display-field">@Model.product_quantity</div>
<div class="display-label">Product Price</div>
<div class="display-field">@Model.product_price</div>
</fieldset>
@using (Html.BeginForm()) {
<p>
<input type="submit" value="Delete" /> |
@Html.ActionLink("Back to List", "Index")
</p>
}
</body>
</html>
Add Create View and select Create option from Scaffold template list:
Create View:
@model RazrMVCApp.Models.Product
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Create</title>
<style type="text/css">
div
{
font-family:Calibri;
}
</style>
</head>
<body>
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Product</legend>
<div class="editor-label">
@Html.LabelFor(model => model.product_category)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.product_category)
@Html.ValidationMessageFor(model => model.product_category)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.product_name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.product_name)
@Html.ValidationMessageFor(model => model.product_name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.product_quantity)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.product_quantity)
@Html.ValidationMessageFor(model => model.product_quantity)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.product_price)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.product_price)
@Html.ValidationMessageFor(model => model.product_price)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div> @Html.ActionLink("Back to List", "Index") </div>
</body>
</html>
After adding the Views, in the Controller we have to call the Views.
1) The Index() action returns all of the product records from database table with
the help of the Entity Framework.
2) The First Edit() action returns selected product detail and second one update
the record in the database.
3) The Details() action returns the details of the selected product.
4) The first Create() action provide you a form in which you can insert the product
details and second one create a new record in the database table.
5) The first Delete() action ask you for a confirmation of delete and second one
delete the records from the table.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RazorMVCApp.Models;
namespace RazorMVCApp.Controllers
{
public class HomeController : Controller
{
ProductDetails product = new ProductDetails();
public ActionResult Index()
{
return View(product.Products.ToList());
}
public ActionResult Edit(int id)
{
return View(product.Products.Where(m => m.product_id == id).Single());
}
[HttpPost]
public ActionResult Edit(FormCollection form)
{
var id = Int32.Parse(form[0]);
var productToUpdate = product.Products.First(m => m.product_id == id);
TryUpdateModel(productToUpdate, new string[] { "product_category",
"product_name", "product_quantity", "product_price" },
form.ToValueProvider());
if (ModelState.IsValid)
{
product.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(productToUpdate);
}
public ActionResult Details(int id)
{
return View(product.Products.Where(m => m.product_id == id).Single());
}
public ActionResult Delete(int id)
{
return View(product.Products.Where(m => m.product_id == id).Single());
}
[HttpPost]
public ActionResult Delete(int id, Product prd)
{
var productToDelete = (from m in product.Products where m.product_id == id
select m).FirstOrDefault();
product.DeleteObject(productToDelete);
product.SaveChanges();
return RedirectToAction("Index", "Home");
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Product prd)
{
if (ModelState.IsValid)
{
product.AddToProducts(prd);
product.SaveChanges();
return RedirectToAction("Index", "Home");
}
else
return View();
}
}
}
After creating a Controller, you can see the output in your browser:
By using above code and information you can easily understand how to use Razor View Syntax with the MVC framework and how to select, insert, delete and update the database records with the entity framework in MVC.
jatin gadhiya
28-Feb-2014just some changes in your code..
remove this line...
product.DeleteObject(productToDelete);
and add this line
product.tblname.Remove(productToDelete);
jatin gadhiya
28-Feb-2014where should i mention that
DeleteObject()
AddToProducts()
i hope your response,
regards,
jatin
anil babu
21-Jun-2013