Click here to Skip to main content
15,860,972 members
Articles / Web Development / ASP.NET
Article

ASP.NET Application Development Using MVC

Rate me:
Please Sign up or sign in to vote.
4.79/5 (24 votes)
23 Feb 2011CPOL5 min read 149.2K   8.3K   56   26
A sample ASP.NET application development using MVC.

Overview

ASP.NET provides the MVC framework as an alternate to the ASP.NET Web Forms pattern for developing web applications. MVC (Model-View-Controller) is a lightweight, highly testable presentation framework that is integrated with the existing ASP.NET features such as Master Pages and Membership-based authentication.

Introduction

The System.Web.Mvc namespace is for ASP.NET MVC. MVC is a standard Design Pattern. MVC has the following components:

  • Controller
  • Classes that handle incoming requests to the application, retrieve model data, and then specify view templates that return a response to the client.

  • Model
  • Classes that represent the data of the application and that use validation logic to enforce business rules for that data.

  • View
  • Template files that your application uses to dynamically generate HTML responses.

Background

In this demonstration, I will design a database using SQL Server Management Studio 2005. I will develop an ASP.NET MVC application and will describe all of its parts.

Let’s Get Started

Open SQL Management Studio 2005. Crate a database and name it Inventory. Design a database table like below:

Image 1

Figure 1
  1. Open Microsoft Visual Studio 2010
  2. Create a new project (File> New> Project> Visual C#): ASP.NET MVC 3 Web Application
  3. Named it ASPNETMVCApplication
  4. Click on the OK button

Image 2

Figure 2
  1. Select a template for Internet Application
  2. View engine to Razor
  3. Create a unit test project to uncheck
  4. Click on the OK button

Image 3

Figure 3

The default project will be created. Now Add Library Package Reference. We will use a .NET Framework data-access technology known as the Entity Framework. The Entity Framework (often referred to as “EF”) supports a development paradigm called code-first. Code-first allows you to create model objects by writing simple classes. You can then have the database created on the fly from your classes, which enables a very clean and rapid development workflow.

We'll start by using the NuGet package manager (automatically installed by ASP.NET MVC 3) to add the EFCodeFirst library to the ASPNETMVCApplication project. This library lets us use the code-first approach. To add Entity Framework reference:

From the Tools menu, select Library Package Manager and then Add Library Package Reference.

Image 4

Figure 4

In the Add Library Package Reference window, click online.

Image 5

Figure 5

Click the NuGet Official package source.

Image 6

Figure 6

Find EFCodeFirst, click on install.

Image 7

Figure 7

Click on I Accept. Entity Framework will install and will add a reference to the project.

Image 8

Figure 8

Click on the Close button.

Image 9

Figure 9

Adding a Model Class

  1. Right click on Models from Solution Explorer
  2. Select Add
  3. Select Class
  4. Name it Book.cs

Image 10

Figure 10

Image 11

Figure 11

Add the following properties in the Book.cs file:

C#
namespace ASPNETMVCApplication.Models
{
    public class Book
    {
        public Int64 Id { get; set; }
        public String Title { get; set; }
        public String ISBN { get; set; }
        public Decimal Price { get; set; }
    }
}

Add another class the way you did for Book.cs and name it BookDBContext.cs. Add a System.Data.Entity namespace reference in the BookDBContext.cs file.

C#
using System.Data.Entity;

Add the following code in the BookDBContext class. And derive it from the DbContext class so that all data operations can be handled by the Books property.

Note: The property name Books must be the same as the database table name Books.

Here is the complete code:

C#
using System;
using System.Web;
using System.Data.Entity;

namespace ASPNETMVCApplication.Models
{
    public class BookDBContext:DbContext
    {
        public DbSet<Book> Books { get; set; } 
    }
}

Add a connection string in the web.config file. Remember, the connection string name must be the same as BookDBContext.

XML
<connectionStrings>
    <add name="BookDBContext" 
      connectionString="data source=Home-PC;
                        uid=sa;pwd=1234;Initial Catalog=Inventory" 
      providerName="System.Data.SqlClient" />
</connectionStrings>

Adding the Controller

  1. Right click on Controller from Solution Explorer
  2. Select Add
  3. Select Controller
  4. Name it BookController
  5. Add action methods for Create, Update, Delete, and Details scenarios to Checked

Image 12

Figure 12

Image 13

Figure 13

It will add the following code:

C#
namespace ASPNETMVCApplication.Controllers
{
    public class BookController : Controller
    {
        //
        // GET: /Book/

        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Book/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Book/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Book/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /Book/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Book/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Book/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Book/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

Now add the following namespaces in the BookController.cs file:

C#
using System.Linq;
using ASPNETMVCApplication.Models;

Declare a global instance variable of the BookDBContext class in the BookController class.

C#
BookDBContext _db = new BookDBContext();

Add the following code in the Index() method:

C#
public ActionResult Index()
{
   var books = from book in _db.Books
               select book;

   return View(books.ToList());
}

This is the LINQ code for getting books and books.ToList() to display the book list in the View.

Now right click on Solution and select Build to build the solution.

Adding the View

  1. Right click in the Index method
  2. Select View
  3. Create a strongly-typed view to Checked
  4. Select Model class to Book (ASPNETMVCApplication.Models)
  5. Scaffold template to List
  6. Click on the OK button

Image 14

Figure 14

It will add the Index.cshtml file.

XML
@model IEnumerable<ASPNETMVCApplication.Models.Book>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th></th>
        <th>
            Title
        </th>
        <th>
            ISBN
        </th>
        <th>
            Price
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
        <td>
            @item.Title
        </td>
        <td>
            @item.ISBN
        </td>
        <td>
            @String.Format("{0:F}", item.Price)
        </td>
    </tr>
}

</table>

Now, add the Create View.

Adding the Create View

  1. Right click on the Create method
  2. Select View
  3. Create a strongly-typed view to Checked
  4. Select Model class to Book (ASPNETMVCApplication.Models)
  5. Scaffold template to Create
  6. Click on the OK button

It will add the Create.cshtml file.

XML
@model ASPNETMVCApplication.Models.Book

@{
    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>Book</legend><div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ISBN)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model =>

Now add the following code in the Create method in the BookController class.

C#
[HttpPost]
public ActionResult Create(FormCollection collection)
{
    try
    {
        Book book = new Book();
        if (ModelState.IsValid)
        {                   
            book.Title = collection["Title"].ToString();
            book.ISBN = collection["ISBN"].ToString();
            book.Price = Convert.ToDecimal(collection["Price"]);

            _db.Books.Add(book);
            _db.SaveChanges();

            return RedirectToAction("Index");
        }
        else
        {
            return View(book);
        }
    }
    catch
    {
        return View(); 
    }
}

Now we will add the Edit View.

Adding the Edit View

  1. Right click on the Edit method
  2. Select View
  3. Create a strongly-typed view to Checked
  4. Select Model class to Book (ASPNETMVCApplication.Models)
  5. Scaffold template to Edit
  6. Click on the OK button

Image 15

Figure 15

It will add the Edit.cshtml file:

XML
@model ASPNETMVCApplication.Models.Book

@{
    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>Book</legend>@Html.HiddenFor(model => model.Id)

        <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ISBN)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model =>

Now add the following code in the Edit method in the BookController class.

C#
public ActionResult Edit(int id)
{
   Book book = _db.Books.Find(id);
   if (book == null)
      return RedirectToAction("Index");

   return View(book);
}

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
   try
   {
       var book = _db.Books.Find(id);

       UpdateModel(book);
       _db.SaveChanges();              
 
        return RedirectToAction("Index");
    }
    catch
    {
        ModelState.AddModelError("", "Edit Failure, see inner exception");
       return View();
    }
}

Now we will add the Details View.

Adding the Details View

  1. Right click on the Edit method
  2. Select View
  3. Create a strongly-typed view to Checked
  4. Select Model class to Book (ASPNETMVCApplication.Models)
  5. Scaffold template to Details
  6. Click on the OK button

Image 16

Figure 16

It will add the Details.cshtml file:

XML
@model ASPNETMVCApplication.Models.Book

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2><fieldset>
    <legend>Book</legend><div class="display-label">Title</div>
      <div class="display-field">@Model.Title</div>
      <div class="display-label">ISBN</div>
      <div class="display-field">@Model.ISBN</div>
      <div class="display-label">Price</div>
      <div class="display-field">@String.Format("{0:F}", Model.Price)</div>
      </fieldset>
<p>
    @Html.ActionLink("Edit", "Edit", new { id=Model.Id }) |
    @Html.ActionLink("Back to List", "Index")
</p>

Add the following code to the Details method of the BookController class.

C#
public ActionResult Details(int id)
{
   Book book = _db.Books.Find(id);

    if (book == null)
      return RedirectToAction("Index");

     return View("Details", book);
}

Now we will add the Delete View.

Adding the Delete View

  1. Right click on the Edit method
  2. Select View
  3. Create a strongly-typed view to Checked
  4. Select Model class to Book (ASPNETMVCApplication.Models)
  5. Scaffold template to Delete
  6. Click on the OK button

Image 17

Figure 17

It will add the Delete.cshtml file.

XML
@model ASPNETMVCApplication.Models.Book

@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2><h3>Are you sure you want to delete this?</h3><fieldset>
    <legend>Book</legend><div class="display-label">Title</div>
    <div class="display-field">@Model.Title</div>
    <div class="display-label">ISBN</div>
    <div class="display-field">@Model.ISBN</div>
    <div class="display-label">Price</div>
    <div class="display-field">@String.Format("{0:F}", Model.Price)</div>
    </fieldset>
@using (Html.BeginForm()) {
    <p>
        <input type="submit" value="Delete" /> |
        @Html.ActionLink("Back to List", "Index")
    </p>
}

Add the following code to the Delete method in the BookController class.

C#
public ActionResult Delete(int id)
{
    Book book = _db.Books.Find(id);
    if (book == null)
        return RedirectToAction("Index");

    return View(book);
}

[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
  Book book = _db.Books.Find(id);
  _db.Books.Remove(book);
  _db.SaveChanges();

  return RedirectToAction("Index");
}

Now run the application. Type /Book in the URL and remember that the port number may be different in your case.

Image 18

Figure 17

Click Create New Link to add a new book.

Image 19

Figure 18

Image 20

Figure 19

This way you can edit, delete, and view details of the books.

Conclusion

This article will help you create your own robust ASP.NET MVC application.

Thank you!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionUpdate data in mvc using sql server Pin
Member 137760631-Sep-18 1:36
Member 137760631-Sep-18 1:36 
QuestionGot Pin
Member 1217270928-Nov-15 4:16
Member 1217270928-Nov-15 4:16 
Question_db.SaveChanges() Pin
Member 1217270928-Nov-15 4:07
Member 1217270928-Nov-15 4:07 
QuestionAbout ConfigurationSettings in Web.config file Pin
Member 1217270928-Nov-15 3:48
Member 1217270928-Nov-15 3:48 
QuestionMy Vote Of 5* Pin
Mas1129-Apr-14 5:54
Mas1129-Apr-14 5:54 
QuestionAwesome-Easy to understood Pin
Appdev(Icode)19-Mar-14 3:32
Appdev(Icode)19-Mar-14 3:32 
GeneralGreat tutorials - -MY vote 5 Pin
DANIAL RAVI29-Jan-14 23:51
DANIAL RAVI29-Jan-14 23:51 
Question5 Star Pin
Yildirim Kocdag18-Sep-13 4:57
Yildirim Kocdag18-Sep-13 4:57 
GeneralMy vote of 5 Pin
ravithejag27-Aug-13 1:15
ravithejag27-Aug-13 1:15 
GeneralMy vote of 5 Pin
Ganapathy A23-Jul-13 23:10
Ganapathy A23-Jul-13 23:10 
Questionhow to add field in atable Pin
abusalehrajib15-Mar-13 23:27
abusalehrajib15-Mar-13 23:27 
QuestionInvalid object name 'dbo.Books'. Pin
sunilvarma.ch2-Mar-13 0:54
sunilvarma.ch2-Mar-13 0:54 
GeneralNice Article Pin
just4sharing27-Nov-12 21:26
just4sharing27-Nov-12 21:26 
QuestionExcellent Pin
Md. Marufuzzaman30-Jun-12 2:13
professionalMd. Marufuzzaman30-Jun-12 2:13 
AnswerRe: Excellent Pin
Abdul Quader Mamun30-Jun-12 2:55
Abdul Quader Mamun30-Jun-12 2:55 
GeneralRe: Excellent Pin
Md. Marufuzzaman30-Jun-12 4:37
professionalMd. Marufuzzaman30-Jun-12 4:37 
Questionvery useful Pin
Rajalingam2225-Jun-12 23:50
Rajalingam2225-Jun-12 23:50 
GeneralError Pin
José Rafael Giraldo Tenorio1-Mar-11 11:19
José Rafael Giraldo Tenorio1-Mar-11 11:19 
General[My vote of 1] nothing new Pin
Seishin#24-Feb-11 21:31
Seishin#24-Feb-11 21:31 
GeneralVery Helpfull Pin
Shahinur Kabir23-Feb-11 23:57
Shahinur Kabir23-Feb-11 23:57 
GeneralRe: Very Helpfull Pin
Abdul Quader Mamun24-Feb-11 1:45
Abdul Quader Mamun24-Feb-11 1:45 
GeneralMy vote of 5 Pin
kdgupta8723-Feb-11 10:31
kdgupta8723-Feb-11 10:31 
GeneralRe: My vote of 5 Pin
Abdul Quader Mamun23-Feb-11 13:47
Abdul Quader Mamun23-Feb-11 13:47 
GeneralOk, great. Pin
ZeroDotNet23-Feb-11 8:05
ZeroDotNet23-Feb-11 8:05 
GeneralRe: Ok, great. Pin
Abdul Quader Mamun23-Feb-11 13:47
Abdul Quader Mamun23-Feb-11 13:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.