Home > DeveloperSection > Articles > First ASP.NET MVC3 Application

First ASP.NET MVC3 Application


ASP.NET MVC ASP.NET MVC 
Ratings:
0 Comment(s)
 6945  View(s)
Rate this:

First ASP.NET MVC3 Application

Here I am going to explain you that how to create simple ASP.NET MVC3 application using razor framework. In this demonstration I will explain you how to create a Model, view and controller. Follow upcoming steps to create first ASP.NET MVC3 application..

1)      Open visual studio 2010 followed by C# project and then selects ASP.NET MVC3 Web application.

2)      Enter you web application name whatever you want and then click on OK. As well as you click on OK button you will find a dialog appears in front of you. This dialog box is created by ASP.NET MVC3. Here you specify which type of framework you want to use and you have to select an appropriate template.

First ASP.NET MVC3 Application

 

In above image you will find two templates one is Empty and other one is Internet Application. If you want to start with built is sample then you can choose Internet Application or if you want to create sample application by yourself then you can choose Empty. I am going to select Empty template with Razor view engine.

Click on OK button.

 

3)      When you click on OK button then you will get following directory structure in your application.

First ASP.NET MVC3 Application

 

Let’s understand meaning of directory which is related with ASP.NET MVC.

a)      Content: We can use this directory to store all Images and CSS related with web sites. As this is only convention which I follow. It’s not mandatory to put it on here. You can put anything on any place or you can follow your own convention. I am following convention which by default comes with ASP.NET MVC.

b)      Controllers: Controller’s are used to mange request and response of ASP.NET MVC website. Each browser request is mapped to a particular controller. Here I will put all controllers required for web site.

c)       Models: In ASP.NET MVC models are C# classes which describe behaviour of your views. We will use Models directory to store all model related with website.

d)      Scripts: This folder contains all jquery files which come with ASP.NET MVC.

e)      Views: This folder contains all views of your web application which finally render on browser.

Now we are ready to create our first ASP.NET MVC application.

Adding Person model in your web application

Here I am going to add first model of this web application. For adding model you can follow these steps.

1)      Right click on Model folder, followed by Add then click on Class option.

2)      After performing this action a dialog box open which ask for entering class name. I had created a class Named Person.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace Excercise1.Models

{

    public class Person

    {

        public int PersonID { get; set; }

        public string PersonName { get; set; }

        public int PersonAge { get; set; }

        public string PersonCity { get; set; }

    }

}

 

 

Here I had created 4 properties in Person class. For creating this demonstration you can write code as follows. I will tell you later what purpose of this code is. For this time you can understand that these fields are used to render strongly typed view. Right now am not going to put any type of validation on models. I will tell you about validations in my next article.

Adding controller in your web application

For adding controller you can follow these steps.

1)      Right click on Controller directory followed by Add followed by controller. Then a dialog box appears where you will provide your controller name. Please note that after giving your controller name don’t remove controller convention. Here I am putting controller name Home.

First ASP.NET MVC3 Application

Here you can see that I had put Home as a controller name and did’t remove Controller convention.

 

                After adding controller following line of codes are written in your controller class.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace Excercise1.Controllers

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

 

        public ActionResult Index()

        {

            return View();

        }

 

    }

}

 

 

Here you can see that  a method named Index(). Delete this method and write down following code in your controller.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using Excercise1.Models;

 

namespace Excercise1.Controllers

{

    public class HomeController : Controller

    {

        [HttpGet]

        public ActionResult AcceptDetails()

        {

            return View();

        }

 

        [HttpPost]

        public ActionResult DisplayDetails(Person person)

        {

            return View(person);

        }

    }

}

 

Here you can see that I had created two methods, one name is AcceptDetails() and another one is DisplayDetails(). One thing important that in AcceptDetails method I had marked HttpGet which assured that we can send direct request to this method and other one is marked as HttpPost which means we cannot send direct request to that method. In other words we can understand that method marked by HttpGet is accessed by URL request and method not marked by HttpPost is not accessed by URL request. One thing more which you need to mention that in DisplayDetails() method I had passed refrense of Person class. For accessing Person class you need to add namespace of your model.

After writing your controller code it’s time to add view for your web application.

Here I am telling you simplest method to add views. Put cursor in method for which you want to add View, then write click followed by Add View option and click on it. An Add View dialog box appears which is as follows.

Note: Before performing this action please build your code so that all classes are available for creating strongly typed view.

First ASP.NET MVC3 Application

Here you can see that View name is automatically display. Select Model class which you had created from Model class dropdown. If you build your code then Model class wills apear. Click on Add button to add view.

Add following code to this view.

@model Excercise1.Models.Person

@{

    ViewBag.Title = "AcceptDetails";

}

<h2>

    This is person accpet form.</h2>

@using (Html.BeginForm("DisplayDetails", "Home", @FormMethod.Post))

{

    @Html.EditorForModel()

    <p>

        <input type="submit" value="Submit Record" />

    </p>

}

 

 

 

Here you can see that I had created from using @Html.Begin form helper. Here you can see that for rendering model I used @Html.EditorForModel() helper which render your models.

Now you had successfully added first model. Now perform same task to add another view. Here I am providing code for another view.

@model Excercise1.Models.Person

 

@{

    ViewBag.Title = "DisplayDetails";

}

 

<h2>Displaying details of person class.</h2>

<p>ID : @Model.PersonID</p>

<p>Name : @Model.PersonName</p>

<p>Age : @Model.PersonAge</p>

<p>City : @Model.PersonCity</p>

 

Here you can see that I am using @Model helper to display details.

After performing this task now it’s time to making some routing configuration. By using routing configuration you told your web application that how to map request to controller and view.

For implementing routing configuration open global.asax file and modify code in RegisterRoutes() method.

public static void RegisterRoutes(RouteCollection routes)

{

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 

            routes.MapRoute(

                "Default", // Route name

                "{controller}/{action}/{id}", // URL with parameters

                new { controller = "Home", action = "AcceptDetails", id = UrlParameter.Optional } // Parameter defaults

            );

 

}

 

 

After performing this step you had create your first ASP.NET MVC3 application using razor framework. Now it’s time to execute your program. Press F5 to execute see it in action.

Here I am putting output.

First ASP.NET MVC3 Application

First ASP.NET MVC3 Application

Thanks to reading this article. I hope this article is useful for beginners . Please provide any comment and suggestion for articles.


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

Follow MindStick