Let us do basic CRUD using MVC4- Rajor View

Niladri.Biswas
Posted by in ASP.NET MVC category on for Beginner level | Points: 250 | Views : 32531 red flag

In this article we will look into the basic CRUD operation using MVC 4 with Entity Framework as Model


 Download source code for Let us do basic CRUD using MVC4- Rajor View

Introduction

In this article we will look into the basic CRUD operation using MVC 4 with Entity Framework as Model

Straight to Experiment

Before doing anything let us first create the database table

-- Drop the table if it exists
IF EXISTS (SELECT * FROM sys.objects WHERE name = N'tbl_Players' AND type = 'U')
    DROP TABLE tbl_Players
GO
SET ANSI_NULLS ON
GO
--Create the table
CREATE TABLE tbl_Players (
	PlayerID INT NOT NULL,
	PlayerName VARCHAR(15),
	BelongsTo VARCHAR(15),
	MatchPlayed INT,
	RunsMade INT,
	WicketsTaken INT
	
CONSTRAINT [PK_PlayerID] PRIMARY KEY CLUSTERED 
(
	[PlayerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Now fire up Visual Studio and choose "ASP.NET MVC 4 Web Application" as the template

Click "OK".Choose "Razor" as the "View Engine" and Click "OK"

The MVC default structure will come up.Choose the Project(MVCApplication1 here) , right click "Add" -> "New Item".

Choose "Data" and choose "Ado.Net Entity Data Model".

Click "Add" .Choose "Generate from Database" as "Model Contents" and click next.

Enter proper SErver Instance, DB Name, and other credentials.If everything is fine then we will receive the below screen.

Give Entities name as "PlayerEntities" and click next

Choose the appropriate table and give model name as "PlayerModel".

Click Finish.And we will get the below screen.

Build the entire solution once.Click on "Controlles" -> Add ->Controller.

And add the below

We can figure out that, a controller by the name "PlayerController.cs" has been created with the the CRUD operation codes and the Respective views has been created.

Open the Index.cshtml and do the below changes

From

to

Since PlayerId is the primary key.

Likewise, open the "PlayerController.cs", and do the similar changes in the Details,Edit,Delete, and DeleteConfirmed methods.

Finally it will look as

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class PlayerController : Controller
    {
        private TestSampleEntities db = new TestSampleEntities();

        //
        // GET: /Default1/

        public ActionResult Index()
        {
            return View(db.tbl_Players.ToList());
        }

        //
        // GET: /Default1/Details/5

        public ActionResult Details(int PlayerID = 0)
        {
            tbl_Players tbl_players = db.tbl_Players.Find(PlayerID);
            if (tbl_players == null)
            {
                return HttpNotFound();
            }
            return View(tbl_players);
        }

        //
        // GET: /Default1/Create

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

        //
        // POST: /Default1/Create

        [HttpPost]
        public ActionResult Create(tbl_Players tbl_players)
        {
            if (ModelState.IsValid)
            {
                db.tbl_Players.Add(tbl_players);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(tbl_players);
        }

        //
        // GET: /Default1/Edit/5

        public ActionResult Edit(int PlayerID = 0)
        {
            tbl_Players tbl_players = db.tbl_Players.Find(PlayerID);
            if (tbl_players == null)
            {
                return HttpNotFound();
            }
            return View(tbl_players);
        }

        //
        // POST: /Default1/Edit/5

        [HttpPost]
        public ActionResult Edit(tbl_Players tbl_players)
        {
            if (ModelState.IsValid)
            {
                db.Entry(tbl_players).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(tbl_players);
        }

        //
        // GET: /Default1/Delete/5

        public ActionResult Delete(int PlayerID = 0)
        {
            tbl_Players tbl_players = db.tbl_Players.Find(PlayerID);
            if (tbl_players == null)
            {
                return HttpNotFound();
            }
            return View(tbl_players);
        }

        //
        // POST: /Default1/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int PlayerID)
        {
            tbl_Players tbl_players = db.tbl_Players.Find(PlayerID);
            db.tbl_Players.Remove(tbl_players);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

So now our application is ready.Let's run it

Click on the "Create New" link to add a new record

We can figure out that a new record has been added

For editing/updating a record, click on the "Edit" button.

Update the record and click "Save"

We can figure out that the record has been editied

For deleting a record, click on the "Delete" button.The "Delete confirmation" window will appear.

Click on the "Delete" button and the record deleted.

Conclusion

So in this article we have seen the basic CRUD operation using MVC 4 with Entity Framework as Model.Hope this will be useful.Thanks for reading.Attached is the zipped file.

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)