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.
Basically we will create an application to save, edit, update, list and search Book records.
In previous articles i explained What is Asp.Net MVC? Its work flow, goals and advantages and The difference between Asp.Net Webforms and Asp.Net MVC. and Dynamically bind asp.net mvc dropdownlist from sql serverdatabase using entity framework and Pass data from controller to view in asp.net mvc and What is the use of viewbag, viewdata and tempdata in asp.net mvc and Create,Read,Update,Delete operation using Asp.Net MVC and Entity Framework
Below is the demo preview of the web application that we are going to build.
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:
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.
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.
Click on image to enlarge |
It will add the required files and folder automatically as shown in image below.
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:
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
- Name 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 { get; set; }
public string BookName { get; set; }
public string Author { get; set; }
public string Publisher { get; set; }
public decimal Price { get; set; }
}
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:
<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.
Next step is to create the controller
- Right click on the Controller folder -> Add -> Controller as shown below.
Click on the image to enlarge |
- Name the controller "BookDetailsController" and Select the following options as shown in image below.
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:
Click on image to enlarge |
Clicking on "Create New" Button will open the screen as shown in image below.
Click on image to enlarge |
Add the details and save some records e.g. as shown in image below:
Click on the image to enlarge |
Clicking on "Details" button you can view the details of any particular record as shown in image below:
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
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.
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
{
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
{
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:
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."
35 comments
Click here for commentsgreat sir, thanks
Replyhello Lalit..
Replythanks for uploading MVC article..I am waiting for some more of it..
Cheers bro
Thanks Ajay..i hope you enjoyed the article and learned the basic of MVC from it..keep reading..:)
ReplyHi Asif Khan..i will create and publish more useful articles on MVC very soon..so stay connected and keep reading..:)
ReplyHello 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.
ReplyHello Faisal..i will upload more articles on MVC soon..keep reading..:)
Replyu created only index wat abt edit n delete ,,,,,,,,
Replyhi ,u didnt create tat edit ,,,,and delete ,,,
Replydo 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
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..
ReplyHollo 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.
ReplyHi 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
ReplyHello 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.
Replyhello sir, this article is really helpful to me.
Replyi would like to read MVC with Linq, MVC without Linq also.
Hello Neeraj, i am glad you liked this article..keep reading and stay connected for more articles on MVC covering all aspects..:)
ReplyHello Sir,
ReplyCan U Plz tell me how to Create CRUD operations in GridView using MVC 4 ASP.NET but without using Entity FrameWork.
thank u sir.this article is very usefulfor me because i m learning mvc.thanks again sir please give and more
ReplyThanks Hemu for your feedback..i am glad you found this article helpful..stay connected and keep reading for more useful updates like this..:)
ReplyHi 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.:)
ReplyHi 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...:)
ReplyThanks for uploading this tutorial can you please help us in Gridview
ReplyPlease Mr. Lalit Raghuvanshi ...
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. :-)
Replythanks sandeep for your feedback..i am glad you liked my articles..stay connected and keep reading..:)
ReplyOne 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...
ReplyBut I need the Search function Can you please tell how can I do that
It is very good starting for initial level understanding of MVC.
ReplyThanks for that :)
thanks ketan..i am glad you found this article useful..stay connected and keep reading for more useful updates...:)
ReplyGreat article..
ReplyThanks..stay connected and keep reading:)
ReplyThanks a lot Lalit.
ReplyIt was very helpul for me.
your welcome..
Replyhi lalith ,
ReplyI 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
I am glad you found my articles on MVC useful..Stay connected for more useful updates like this..
Replyreallly its very helpful for me
ReplyThanks for your feedback..:)
Replythank you so much this artical help me lots !!
ReplyThanks for your feedback..Stay connected and keep reading for more useful updates
ReplyIf 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..