In the previous chapter, we have learned about how we can use scaffolding techniques to create CRUD application. Today, we will see the code to create new CRUD application in ASP.NET MVC.
I am going to use same data, table and entity model classes, which I have used in previous chapters.
Code for displaying data:
One of the most important part of any application is to display data. How you will display data? As we have learned in previous chapters, ASP.NET MVC works on the action result and view result. So first and foremost thing is that we need to create a method in controller that will result view result. I have created an object of entity class as following:
private TestEntityEntities db = new TestEntityEntities();
Then, I have written a method called Index as follows:
public ViewResult Index()
{
return View(db.Users.ToList());
}
Here, you can see in the above method that we are returning a list of user model classes as view result. Now, it is time to create a view file for that. So, I have created a index.cshtml file as follows:
@model IEnumerable<MvcApplication3.Models.User>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
UserName
</th>
<th>
FirstName
</th>
<th>
LastName
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.UserId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.UserId })
</td>
</tr>
}
</table>
Here in the above code, you can see we have created a tightly coupled view with User model classes we have. I have created this view in Razor syntax as we have used razor syntax for the whole series.
On the top, I have created one action link for Create New, which redirects it back to create view, which we are going to create further. After that there is a ‘for’ loop which will integrate for all the users and will create a table to display user data. In addition, I have three other actions link for redirecting people to Edit, Delete & View that we are going to create after this.
So once you put URL in browser, it will call the Index method of controller and send user data to respective view and view will iterate through data and will show the data in browser.
So, once you run this application it will look like following:

Code for adding new data:
Now we are doing with the code for displaying user data, it’s time to create a code for new data. So let’s first create a view that will hold the structure to add new data and then we will create action result and view result method.
So here, I have created a new view called Create.shtml and following is a code for that:
@model MvcApplication3.Models.User
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<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>User</legend>
<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Here, in the above code you can see that we have again strongly typed view. Here you can see that I have created html form with the respective fields and validation. It will fire validation as per our rules defined in model classes. Let’s write server side for this. We have to write two methods for that. Once will return a blank view and another will be method which will actually add the data into the database via entity framework datacontext. Following is a code for that:
public ActionResult Create()
{
return View();
}
This method will return a empty view when anybody clicks on create new from the user grid page. Another action method in User controller method, which will add data into the database. Following is a code for that:
[HttpPost]
public ActionResult Create(User user)
{
if (ModelState.IsValid)
{
db.Users.AddObject(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
Here in the above code, you can see that there is http post attribute is at the top of the action result method as we are using post method to submit font. Also, in the code you can see there is check for validation and then we are adding data. After adding data, it will return to Index view. Once you run this application your add form will look like below:

Code for editing data:
Now it’s time for the edit part. Here we need to write a code, which will first bring view with existing data and once we have completed editing it will update existing data.
Following is a razor code for edit view. Again, it’s a strongly typed view:
@model MvcApplication3.Models.User
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<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>User</legend>
@Html.HiddenFor(model => model.UserId)
<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Here, in the above code you can see it’s almost similar as add new view.
Now it’s time to write a server side code. We need to write two-action result method to edit data. First, one will return existing data to view and following is a code for that:
public ActionResult Edit(int id)
{
User user = db.Users.Single(u => u.UserId == id);
return View(user);
}
In the above code, you can see that first we have fetched the current user data and returning that model class with user view and our razor will load data according to it.
Another action result will be for updating existing data. Following is a code for that:
[HttpPost]
public ActionResult Edit(User user)
{
if (ModelState.IsValid)
{
db.Users.Attach(user);
db.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
Here you can see in the above code, we have used post method of form to submit data to server and putted HttpPost attribute. After that, we have checked that Model is valid or not if it is validate then we changing data with savechanges method of entity framework data context save method. Once you run the application click on this it will load form, like below:

Once you click on save it will update the data and return back to user grid.
Code for delete data:
Now it’s time to write code for the deletion of data. So we have create a view for deletion which asked for confirmation of deletion and then once user confirms data it will delete data. Following is a code for that:
@model MvcApplication3.Models.User
@{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you want to delete User?</h3>
<fieldset>
<legend>User</legend>
<div class="display-label">UserName</div>
<div class="display-field">
@Html.DisplayFor(model => model.UserName)
</div>
</fieldset>
@using (Html.BeginForm()) {
<p>
<input type="submit" value="Delete" /> |
@Html.ActionLink("Back to List", "Index")
</p>
}
In the above code for view, you can see we are displaying username and asking for the confirmation and in Html form we have putted two things, one is delete submit button and second is 'back to list action link' to redirect to back to user grid page. Now, let’s write server side for that. Here also, we need two-action result method. First one will display confirmation information and another is for actually performing delete operation with the help of entity framework.
Following is the code for that:
public ActionResult Delete(int id)
{
User user = db.Users.Single(u => u.UserId == id);
return View(user);
}
This return a confirmation view with user type and following action result method will perform action deletion of data from database.
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
User user = db.Users.Single(u => u.UserId == id);
db.Users.DeleteObject(user);
db.SaveChanges();
return RedirectToAction("Index");
}
Here you can we have used two attributes - Httpost, as we are posting data view post form method and actionname, which will let controller know when you call this method. So this method will be called for delete method when post from with userid that needs to be deleted and we will delete data with the help of deleteobject method with entity framework. Once you run application and click on ‘delete’ it will ask for confirmation like following:

Once you click on delete, it will delete the data and redirected to user grid.
That is it. We are done with CRUD operation with asp.net and entity framework. In the next chapter, we will learn about URL routing in ASP.NET MVC.