Wednesday, October 29, 2014

Show data from a database table content in MVC 4.0 razor

In this MVC tutorial post I will show you how to show a database content to a page in MVC 4.0. So for those who are not aware of MVC (Model View Controller) concept you can visit this post  as a reference.

So first create a new MVC project. Select Razor as your View engine.
Create a new database named what ever you want and add a new table named tblEmployee.Design your database as following.


And after that add an EmployeeController in the Controller folder.

And after that add an Empployee.cs in the Model folder. Add the following code into the Employee.cs.

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MvcApplication1.Models
{
    [Table("tblEmployee")]
    public class Employee
    {
        [Key]
        public int empid { get; set; }
        public string name { get; set; }
        public string dept { get; set; }
    }

}

I set the Table attribute to tblEmployee as to connect the tblEmployee table with Employee class. Normally it takes the class name as the class name. But here our class name is differ from class name. So I did it.
Now add another class named EmployeeContext.cs into the Model folder again. Its is to connect the connection string in Web.Config file.
Write down the following code in the EmployeeContext.cs
using System.Data.Entity;

public class EmployeeContext : DbContext
{
    public DbSet employee { get; set; }
}

Add the connection string in the web.config as a name EmployeeContext. Now come back to EmpployeeController. Add a View of Indes Action. Doing this choose create a strongly typed view and select Employee. If Employee is not showing then do not get panic. Just build the solution once. It will show the Employee in to the drop down list to choose. Now in the Index.cshtml in View add the following code.
@using MvcApplication1.Models;
@using System.Web.Mvc;

@model IEnumerable

@{
    ViewBag.Title = "Index";
}

All Employee Details

@foreach(Employee emp in @Model) { }
@emp.dept @emp.name @emp.dept

In the EmployeeController write down the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Index()
        {
            EmployeeContext emp = new EmployeeContext();
            List employee1 = emp.employee.ToList();

            return View(employee1); // return list of employee
        }
    }
}

Now run your project and enter the URL localhost://Employee/Index

Download the full source code here.

0 comments:

Post a Comment

Popular Posts

Pageviews