MVC Application using Razor View and Entity Framework

This artice simply demonstrate how to create ASP.NET MVC application using razor view engine and how to use data access technology i.e. Entity Framework(EF) while creating ASP.NET MVC 3 application.
Before creating the MVC 3 Application in Visual studio create a table in the database with name and structure as given below:
CREATETABLE [dbo].[Students]
(
      [ID] [INT] IDENTITY PRIMARY KEY,
      [NAME] [VARCHAR](50),
      [AGE] [INT],
      [CITY] [VARCHAR](50)
)

 

You can create applications using either Visual Basic or Visual C# as the programming language. Select Visual C# on the left and then select ASP.NET MVC 3 for this sample. Name your project “MvcSampleApp” and then click OK.

In the New ASP.NET MVC 3 Project dialog box, select Internet Application. Check Use HTML5 markup and leave Razor as the default view engine.

 

In Solution Explorer, right click the Models folder, select Add, and then select Class.
Name the class Student.
Add the following four properties to the Student class:
public class Student
{
        public int ID
        {
            get;
            set;
        }
 
        public string NAME
        {
            get;
            set;
        }
 
        public int AGE
        {
            get;
            set;
        }
 
        public string CITY
        {
            get;
            set;
        }
}

 

We’ll use the student class to represent student in a database. Each instance of a Student object will correspond to a row within a database table, and each property of the Student class will map to a column in the table.
In the same file, add the following StudentDbContext class
public class StudentDbContext : DbContext
{
        public DbSet<Student>Students
        {
            get;
            set;
        }
}

 

The StudentDbContext class represents the Entity Framework student database context, which handles fetching, storing, and updating Student class instances in a database. The StudentDbContext derives from the DbContext base class provided by the Entity Framework.

 

After adding Model class, open the application root Web.config file.
Add the following connection string to the <configuration> element in the Web.config file.

 

<connectionStrings>
    <add name=StudentDbContextconnectionString=Data
Source=.\SQLEXPRESS; Initial Catalog=sample; Integrated Security=true;
providerName=System.Data.SqlClient/>
</connectionStrings>

 

Add a controller class.
In Solution Explorer, right-click the Controllers folder and then select Add Controller.

 

Select the following options:
·   Controller name: StudentController.
·   Template: Controller with read/write actions and views, using Entity Framework.
·    Model class: Student (MvcSampleApp.Models).
·    Datacontext class: StudentDbContext (MvcSampleApp.Models).
·    Views: Razor (CSHTML). (The default.)

 

Click Add. Visual Web Developer creates the following files and folders:
·   A StudentController.cs file in the project’s Controllers folder.
·   A Student folder in the project’s Views folder.
·   Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml in the new Views\Student folder.

 

After adding StudentController, add a HomeController (the default controller) as shown below:

Modify the Index action of HomeController as shown below:
public class HomeController : Controller
{
        public ActionResult Index()
        {
            return RedirectToAction(“Index”, “Student”);
        }
}

 

 
It will redirect to the Index method of Student controller.

 

Now run or debug your application and add some student records. It will something look like as shown below:

 

You can also edit and delete the records and view the details of student.

Further, I am going to explain how to add search functionality in order to search the student by their name and city.

 

Add the following code in the Index.cshtml to implement and display the search functionality to the user. Add the following code below the @Html.ActionLink:

 

@Html.ActionLink(“Create New”, “Create”)
@using (Html.BeginForm(“Index”,”Student”,FormMethod.Get))
{
     <p>City: @Html.DropDownList(“cityList”,“All”)
Name: @Html.TextBox(“stname”)</p>
     <input type=”submit” value=”Search” />
}

 

 
Modify the Index action of StudetController as shown below:

 

public ViewResult Index(string cityList, string stname)
{
            //select all student records
            var students = fromin db.Students
                           select s;
            //get list of cities
            var citylist = from c in students
                           orderby c.CITY
                           select c.CITY;
             //set distinct list of cities in ViewBag property
             ViewBag.cityList = new SelectList(citylist.Distinct());

 

             //search record by city and name
             if (!string.IsNullOrEmpty(stname))
students = students.Where(m => m.NAME.Contains(stname));
             if (!string.IsNullOrEmpty(cityList))
students = students.Where(m => m.CITY == cityList);
            return View(students);
 }

 

Run an application. Now you can easily search the records of student on the basis of their names or city or both.

 

 

Thanks for reading this article.

 

 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s