Home > DeveloperSection > Articles > MVC Application using Razor View

MVC Application using Razor View


ASP.NET MVC ASP.NET MVC 
Ratings:
2 Comment(s)
 6869  View(s)
Rate this:

MVC Application using Razor View

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:

CREATE TABLE [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.

MVC Application using Razor View

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.

MVC Application using Razor View

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="StudentDbContext"connectionString="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.

MVC Application using Razor View

Select the following options:

·         Controller name: StudentController.

·         Template: Controller with read/write actions and views, using Entity Framework.

·         Model class: Student (MvcSampleApp.Models).

·         Data context class: StudentDbContext (MvcSampleApp.Models).

·         Views: Razor (CSHTML). (The default.)

MVC Application using Razor View

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.

MVC Application using Razor View

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

MVC Application using Razor View

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:

MVC Application using Razor View

 

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

 

 

MVC Application using Razor View

 

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 = from s in 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.

 

MVC Application using Razor View

 

Thanks for reading this article.

 


MV Razor View

By Carl Pieterson on   4 years ago
nice article.

Nice Article!

By AVADHESH PATEL on   3 years ago
Hi Mr. Rohit!

This article is very helpful for beginner in MVC. I have read your all articles essentially related to MVC. 
I have one question related to ajax with mvc in mvc 4. Can I create menu tab (e.g. Home, Contact, About us etc.) using partial view for avoiding post back? If yes, then what is drawback of this way, if no, then any alternate way to achieve this.

Thanks for sharing your knowledge. 
keep it up!  

Don't want to miss updates? Please click the below button!

Follow MindStick