Reader Level:
Articles

Database Programming in MVC 3 in 5 Minutes

By Abhimanyu K Vatsa on February 13, 2012
In this article you are going to learn Database Programming in MVC 3 in 5 minutes. In this article I will take the advantage of Entity Framework 4.1 code first to create my database. I will also take the advantage of Scaffold templates. You can also watch the audio-less video given in the article.
  • 2
  • 0
  • 46886

Introduction

In this article you are going to learn Database Programming in MVC 3 in 5 minutes. In this article I will take the advantage of "Entity Framework 4.1 Code First" to create my database. I will also take the advantage of Scaffold templates.

There are three ways to create MVC Projects:

  1. Database First

  2. Model First

  3. Code First

In this article I'll be using Code First.

I will keep my ideas as simple as possible so that any newcomers can also understand this. I'm going to write this using a step by step approach. So, let's start.

Step 1: Creating New MVC Project

Create a new MVC 3 Project, File > New > Project. In this window select the language as a C# and project template as "ASP.NET MVC3 Web Application", change the project location if you wish or leave it as the default.

1.gif

When you click on OK, you will get the following screen. In this screen choose the project template as "Internet Application", View engine as "Razor" and check to use "HTML5 Markup", and at the end click on OK.

2.gif

When you click on OK button you will get following project files and folders by default.

3.jpg

Now let's move to next step.

Step 2: Adding Model

New add a new model by right clicking on Model > Add > Class and name it as "Contact.cs". Type the following code as given in screenshot.

4.jpg

In the above screen I have created two separate sections, one for properties and another for database context.

Note: If you want to learn some more quick way to add the properties, here you go.

Step 3: Adding Controller

Right-click on the controller in Solution Explorer > Add > Controller. It will pop a window, here you need to change the controller name and Scaffolding templates as given in the image.

5.jpg

When you click on OK button above, it will add a new Controller to the project having many Action Methods (Index, Details, Create, Edit and Delete) and HttpPost Controllers for Create, Edit and Delete methods.

Step 4: Adding View for "Create Action" & Editing its HttpPost

To add a view for a Create Action you need to right-click in the Create Action and navigate to "Add View".

Note: Because we are going to create a strongly typed view, we must build the project from the Build menu before adding views.

6.jpg

When you click on "Add View", it will show the following window; please select options as directed in image below.

7.jpg

When you click on Add button, you can see the system adds one View in your project Explorer (Views > Contact > Create.cshtml).

Now, edit the HttpPost Create Action so that it can save the data in the database. Here is the modified code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;
namespace MvcApplication2.Controllers
{
    public class ContactController : Controller
    {
        ContactContext db = new ContactContext();

        //
        // GET: /Contact/

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

        //
        // GET: /Contact/Details/5

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

        //
        // GET: /Contact/Create

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

        //
        // POST: /Contact/Create

        [HttpPost]
        public ActionResult Create(Contact person)
        {
            db.Contacts.Add(person);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        //
        // GET: /Contact/Edit/5

        // rest coding….

    }
}

I have added a namespace:

using MvcApplication2.Models;

And modified the HttpPost Create Action to:

        [HttpPost]
        public ActionResult Create(Contact person)
        {
            db.Contacts.Add(person);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

Now, if you have done the above then you can run the application and it will add (create) the records in database but still you can't view them because we have not listed them. So, let's list the records too, and then we will run it.

Step 5: Adding View for "Index Action" by modifying it

In this step you need to modify the Index Action, here is the modified code:

        public ActionResult Index()
        {
            var contact = db.Contacts.ToList();
            return View(contact);
        }

Now, add the view for it as directed in Step 3 also, find the image below.

8.jpg

When you click on Add button, you can see that the system has added one View to your project explorer (Views > Contact > Index.cshtml).

Now run the application and navigate to "http://localhost:4329/Contact". Your port number in the URL might be different.

Step 6: Adding New Record & Listing

You cannot see any records as we have not added any, so let's click on "Create New" to add the record.

Look at the image; I have added a new record.

9.jpg

Step 7: Required Field Validation

Now, if you try to insert a blank record it will show you an error only for the Date field, we have not even added any validation. Remember, in the model class (in Step 2) we have created all properties using string type data for Name, Address and Mobile but for the DataDate it is DateTime, that's why the database can't accept invalid dates. Now, modify the Step 2 code so that validation can work for rest fields also. Even we will add maximum length to string. Here is the modified code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication2.Models
{
    public class Contact
    {
        public int ID { get; set; }

        [Required]
        [StringLength(20)]
        public string Name { get; set; }

        [Required]
        [StringLength(20)]
        public string Address { get; set; }

        [Required]
        [StringLength(12)]
        public string Mobile { get; set; }

        public DateTime DataDate { get; set; }
    }

    public class ContactContext : DbContext
    {
        public DbSet<Contact> Contacts { get; set; }
    }
}

Four modifications are made in the above code:

  1. Added a namespace "using System.ComponentModel.DataAnnotations;".

  2. Made Name field as required and its length to 20.

  3. Made Address field as required and its length to 20.

  4. Made Mobile field as required and its length to 12.

Now, let's try to insert records without filling it in completely, it will show you the following errors:

11.jpg

Step 8: Editing Records

To edit the records, let's modify its Edit Action and its HttpPost handler. Here is the modified one.

        public ActionResult Edit(int id)
        {
            var contact = db.Contacts.Find(id);
            return View(contact);
        }

        [HttpPost]
        public ActionResult Edit(Contact contact)
        {
            db.Entry(contact).State = System.Data.EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

Now, add the view for the edit action by right-clicking in the above code (not in HttpPost), find the image below.

12.jpg

Run the project, now you can edit the records there.

Step 9: Details of Record

To view the details of any record, we need to modify its action to:

        public ActionResult Details(int id)
        {
            var contact = db.Contacts.Find(id);
            return View(contact);
        }

And add the view for the Details Action, as given in the screen below:

13.jpg

Now, run the application and check it.

Step 10: Deleting Record

To delete the record, we need to modify its action to:

        public ActionResult Delete(int id)
        {
            var contact = db.Contacts.Find(id);
            return View(contact);
        }

        //
        // POST: /Contact/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, Contact contact)
        {
            var dcontact = db.Contacts.Find(id);
            db.Contacts.Remove(dcontact);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

And add the view for the Delete Action, as given in the screen below:

14.jpg

Now, we are done with all the coding, let's run the project and check all functionality.

Video Reference

image001.jpg

I will recommend you to download the attached file and look at the complete coding. You can also watch the audio-less video given above. I hope you like it. Thanks.

Article Extensions
Contents added by ram ji on Apr 29, 2013
Abhimanyu K Vatsa

Microsoft MVP | Author | IT Faculty | Student of M.Tech. IT | Blogs at ITORIAN.COM

Personal Blog: http://www.itorian.com
COMMENT USING

Trending up