articles

Home / DeveloperSection / Articles / MVC Application using Razor View

MVC Application using Razor View

Chris Anderson 10741 10-Sep-2012

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 ViewFurther, 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.

 


Updated 07-Sep-2019
hi I am software developer at mindstick software pvt. ltd.

Leave Comment

Comments

Liked By