Asp.Net MVC 4 application to Create,Read,Update,Delete and Search functionality using Razor view engine and Entity Framework

Introduction: In this tutorial article you will learn How to create Asp.net MVC 4 web application having CRUD (Create, Read, Update, and Delete), View details and Search functionality using Razor view engine, Entity Framework(EF) and SQL SERVER Database.

Asp.Net MVC Insert, Edit, Update, Delete, List and Search functionality using Razor view engine and Entity Framework
Click on image to view enlarged demo

Requirements: I am using Visual Studio 2010 for accomplishing this application. You need to install the following components before completing this application:
But if you are using Visual Studio 2012 then you don't need to install anything because it is having all the required components by default.

Implementation: Let's create our first Asp.Net MVC web application.
  • Open Visual Studio -> File -> New -> Project
  • Select you preferred language either Visual C# or Visual Basic. For this tutorial we will use Visual C#.
  • Name the project "MvcBookApp". Specify the location where you want to save this project as shown in image below. Click on Ok button. 
Asp.Net MVC Insert, Edit, Update, Delete, List and Search functionality using Razor view engine and Entity Framework
Click on the image to enlarge
  • A "New ASP.NET MVC 4" project dialog box having various Project Templates will open. Select Internet template from available templates. Select Razor as view engine as shown in image below. Click on Ok button.
Asp.Net MVC Insert, Edit, Update, Delete, List and Search functionality using Razor view engine and Entity Framework
Click on image to enlarge
It will add the required files and folder automatically as shown in image below.

Asp.Net MVC Insert, Edit, Update, Delete, List and Search functionality using Razor view engine and Entity Framework
Click on image to enlarge
Can you believe you have created your first MVC project without doing anything? But yes working MVC project is created having default template. 

You can run the application using F5 or from the Debug menu of Visual Studio select Start Debugging. You will see the page as shown below:

Asp.Net MVC Insert, Edit, Update, Delete, List and Search functionality using Razor view engine and Entity Framework
Click on image to enlarge

As we are using default template, you can see the links to the Home, About and Contact pages that are all functional.
But our aim is to create a web application to manage Book records. So we need to create the Model class that will automatically create the table in the database having the columns as mentioned in the form of properties in the class.

Creating Model

So let's create the model
  • Right Click on the Models folder of the project -> Add -> Class as shown in image below 
    Asp.Net MVC Insert, Edit, Update, Delete, List and Search functionality using Razor view engine and Entity Framework
    Click on image to enlarge
  • Name the class "BookDetail.cs"
And write the following code in the class BookDetail.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;

namespace MvcBooksApp.Models
{
    public class BookDetail
    {     
            [Key]
            public int BookId { getset; }
            public string BookName { getset; }
            public string Author { getset; }
            public string Publisher { getset; }
            public decimal Price { getset; }
        }
        public class BookDetailContext : DbContext
        {
            public DbSet<BookDetail> BookDetails
            {
                get;
                set;
            }
        }
    }

 Note: If you get the error "The type or namespace name 'DbContext' could not be found (are you missing a using directive or an assembly reference?) " then read the article "Error Solution:The type or namespace name 'DbContext' could not be found (are you missing a using directive or an assembly reference?)"
  • Now it's time to create the database. So launch SQL SERVER and create a database and name it "Books_DB"
  • In the web.config file of the root directory of our project, create the connection string in the <configuration> tag as:
<connectionStrings>
    <add name="BookDetailContext" connectionString="Data Source=lalit;Initial Catalog=Book_DB;Integrated Security=True"/>
  </connectionStrings>

Note: Replace the Data Source and Initial Catalog as per your application.
  • Build the project first before going further. Go to Build menu -> Build MvcBooksApp.
 Creating Controller

Next step is to create the controller   
  • Right click on the Controller folder -> Add -> Controller as shown below. 
Asp.Net MVC Insert, Edit, Update, Delete, List and Search functionality using Razor view engine and Entity Framework
Click on the image to enlarge
  • Name the controller "BookDetailsController" and Select the following options as shown in image below. 
Asp.Net MVC Insert, Edit, Update, Delete, List and Search functionality using Razor view engine and Entity Framework
Click on image to enlarge

 ·         Controller name: BookDetailsController.
·        Template: MVC Controller with read/write actions and views, using Entity Framework.
·        Model class: BookDetail (MvcBooksApp.Models)
·        Data context class: BookDetailContext (MvcBooksApp.Models)
·        Views: Razor (CSHTML).

Note: Model class and Data Context class will not appear until you build the project.

On clicking Add Button, Visual studio will create the following files and folder under your project.
  • A BookDetailsController.cs file in the Controllers folder of the project. 
  • A BookDetails folder in the Views folder of the project. 
  • And also the Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml in the Views\ BookDetails folder.
Congrats you have created the MVC application having Create, Read, Update and Delete (CRUD) functionality that the Asp.Net MVC automatically created so the phenomenon of creating CRUD action methods and views automatically is called Scaffolding.

Run the application using F5 and navigate to BookDetails controller by appending BookDetails to the URL in the browser: http://localhost:1860/Bookdetails/. You will see the page as shown in image below:

Asp.Net MVC Insert, Edit, Update, Delete, List and Search functionality using Razor view engine and Entity Framework
Click on image to enlarge
Clicking on "Create New" Button will open the screen as shown in image below.

Asp.Net MVC Insert, Edit, Update, Delete, List and Search functionality using Razor view engine and Entity Framework
Click on image to enlarge
Add the details and save some records e.g. as shown in image below:

Asp.Net MVC Insert, Edit, Update, Delete, List and Search functionality using Razor view engine and Entity Framework
Click on the image to enlarge
Clicking on "Details" button you can view the details of any particular record as shown in image below:
Asp.Net MVC Insert, Edit, Update, Delete, List and Search functionality using Razor view engine and Entity Framework
Click on image to enlarge
You can also edit any particular record by clicking on the "Edit" button at the bottom of the record details or come back to the main page by clicking on "Back to List" button.
From the main BookDetails page clicking on the Edit button enables you to edit the record as shown in image below
Asp.Net MVC Insert, Edit, Update, Delete, List and Search functionality using Razor view engine and Entity Framework
Click on the image to enlarge
Make the changes and update the record.
Similarly clicking on the "Delete" button allows you to delete the record.

Implementing Searching functionality
  • Now going further we will also implement the Searching functionality in this application so that we can search the book records by Publisher or Book Name.
So in the Views folder of the project -> BookDetails -> Index.cshtml
Add the following lines
 @using (Html.BeginForm("Index","BookDetails",FormMethod.Get))
        {    
         <p>Publisher: @Html.DropDownList("Publishers""All")  
           Book Name: @Html.TextBox("strSearch")  
         <input type="submit" value="Search" /></p>
        }
below the line @Html.ActionLink("Create New""Create")

So it should look like:

  @Html.ActionLink("Create New", "Create")
    @using (Html.BeginForm("Index","BookDetails",FormMethod.Get))
        {    
         <p>Publisher: @Html.DropDownList("Publishers", "All")  
           Book Name: @Html.TextBox("strSearch")  
         <input type="submit" value="Search" /></p>
        } 
  • In the Controller folder -> BookDetailsController.cs , comment or remove the code
public ActionResult Index()
        {
            return View(db.BookDetails.ToList());
        }
and add the method as:

public ViewResult Index(string Publishers, string strSearch)
        {
            //Select all Book records
            var books = from b in db.BookDetails
                           select b;

            //Get list of Book publisher
            var publisherList = from c in books
                           orderby c.Publisher
                           select c.Publisher;

            //Set distinct list of publishers in ViewBag property
            ViewBag.Publishers = new SelectList(publisherList.Distinct());

            //Search records by Book Name 
            if (!string.IsNullOrEmpty(strSearch))
                books = books.Where(m => m.BookName.Contains(strSearch));

            //Search records by Publisher
            if (!string.IsNullOrEmpty(Publishers))
                books = books.Where(m => m.Publisher == Publishers);
            return View(books);
        }
  • Now time to run the application. Go to Controller folder -> HomeController replace the below index method
public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            return View();
        }
With the method
public ActionResult Index()
        {
            return RedirectToAction("Index""BookDetails");           
        }

Now run the application and you will see the results as shown in the image below:

Asp.Net MVC Insert, Edit, Update, Delete, List and Search functionality using Razor view engine and Entity Framework
Click on the image to enlarge

Now over to you:
" I hope you have created your Asp.Net MVC application successfully and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates." 
Previous
Next Post »

35 comments

Click here for comments
Unknown
admin
November 12, 2013 ×

great sir, thanks

Reply
avatar
Unknown
admin
November 12, 2013 ×

hello Lalit..
thanks for uploading MVC article..I am waiting for some more of it..
Cheers bro

Reply
avatar
November 13, 2013 ×

Thanks Ajay..i hope you enjoyed the article and learned the basic of MVC from it..keep reading..:)

Reply
avatar
November 13, 2013 ×

Hi Asif Khan..i will create and publish more useful articles on MVC very soon..so stay connected and keep reading..:)

Reply
avatar
Unknown
admin
November 14, 2013 ×

Hello sir. I read your blog and like it. but in this tutorial i did not understand properly can you please upload some other article related to mvc without any Crude Operation from basic level. in this article you did not mention how will i create entity framework.

Reply
avatar
November 14, 2013 ×

Hello Faisal..i will upload more articles on MVC soon..keep reading..:)

Reply
avatar
Unknown
admin
November 19, 2013 ×

u created only index wat abt edit n delete ,,,,,,,,

Reply
avatar
Unknown
admin
November 19, 2013 ×

hi ,u didnt create tat edit ,,,,and delete ,,,


do any ,,,binding data to dropdown from database ,,,selected item ,,,,,when i insert ,,,,,tried of this ,,,,am binding data,,,but value or item not selecting in droplist ,,,,plz solve this

Reply
avatar
November 20, 2013 ×

Hello Santhosh Patil..have you followed the article fully? Scaffolding automatically creates the index,edit,delete and details functionality. When you will follow the article, they will be automatically created..

Reply
avatar
November 20, 2013 ×

Hollo sir, I want to learn MVC in details so please upload more articles in MVC. I read your articles it's very usefull so sir help me.


Reply
avatar
November 20, 2013 ×

Hi Anil..i am working on MVC articles so that the reader like you can learn the MVC..I will soon publish some more articles..so keep reading

Reply
avatar
Unknown
admin
November 30, 2013 ×

Hello sir, I also work with MVC and i'm using ajax to post the data to controller. but image ulpoaded is not posting to controller . Please help me.

Reply
avatar
Neeraj_ Negi
admin
December 10, 2013 ×

hello sir, this article is really helpful to me.
i would like to read MVC with Linq, MVC without Linq also.

Reply
avatar
December 10, 2013 ×

Hello Neeraj, i am glad you liked this article..keep reading and stay connected for more articles on MVC covering all aspects..:)

Reply
avatar
Anonymous
admin
January 03, 2014 ×

Hello Sir,
Can U Plz tell me how to Create CRUD operations in GridView using MVC 4 ASP.NET but without using Entity FrameWork.

Reply
avatar
Unknown
admin
March 18, 2014 ×

thank u sir.this article is very usefulfor me because i m learning mvc.thanks again sir please give and more

Reply
avatar
March 18, 2014 ×

Thanks Hemu for your feedback..i am glad you found this article helpful..stay connected and keep reading for more useful updates like this..:)

Reply
avatar
Unknown
admin
March 22, 2014 ×

Hi Lalit..Thank you for your articles...Try to update your Posts on MVC..we are waiting for those...at least give me one mvc article for a day.:)

Reply
avatar
March 23, 2014 ×

Hi rahul..thanks for appreciating my work...it is always nice to hear that someone liked my work..I will try to publish more articles on MVC...:)

Reply
avatar
Anonymous
admin
April 25, 2014 ×

Thanks for uploading this tutorial can you please help us in Gridview
Please Mr. Lalit Raghuvanshi ...

Reply
avatar
Unknown
admin
May 19, 2014 ×

Greatly appreciated the way you learnt, but this is not at all much ... lets dig more .. so now i would be your sincere reader of your blogs .. thanks again, having pleasures for such true and honest articles. :-)

Reply
avatar
May 20, 2014 ×

thanks sandeep for your feedback..i am glad you liked my articles..stay connected and keep reading..:)

Reply
avatar
Anonymous
admin
June 27, 2014 ×

One thing to ask that is not searching the record from the model, but that is filtering the record, where on the you have all the list of records...

But I need the Search function Can you please tell how can I do that

Reply
avatar
Ketan Patel
admin
August 02, 2014 ×

It is very good starting for initial level understanding of MVC.
Thanks for that :)

Reply
avatar
August 05, 2014 ×

thanks ketan..i am glad you found this article useful..stay connected and keep reading for more useful updates...:)

Reply
avatar
Anonymous
admin
August 20, 2014 ×

Great article..

Reply
avatar
August 20, 2014 ×

Thanks..stay connected and keep reading:)

Reply
avatar
Anonymous
admin
August 25, 2014 ×

Thanks a lot Lalit.
It was very helpul for me.

Reply
avatar
Anonymous
admin
January 17, 2015 ×

hi lalith ,
I am a beginners of MVC. After a lot of google search i found this website . it helps a lot for me and all the beginners of MVC . Thank you very much once again and waiting for new updates on MVC.

Keep share the treasure of knowledge


Reply
avatar
January 22, 2015 ×

I am glad you found my articles on MVC useful..Stay connected for more useful updates like this..

Reply
avatar
Unknown
admin
March 09, 2015 ×

reallly its very helpful for me

Reply
avatar
March 09, 2015 ×

Thanks for your feedback..:)

Reply
avatar
Unknown
admin
May 26, 2016 ×

thank you so much this artical help me lots !!

Reply
avatar
June 02, 2016 ×

Thanks for your feedback..Stay connected and keep reading for more useful updates

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..