Getting Started Tutorial with ASP.NET MVC

This article gives you step by step tutorial to create first ASP.NET MVC application using feature like Controller and View.

ASP.NET MVC is an architectural pattern. It allows you to create dynamic websites with clean separation of concerns and full control over HTML markup. This also gives you a feature like TDD friendly development.


Follow below steps to create your first ASP.NET MVC application

Open Visual Studio

Click on File -> New -> Project

From Installed Templates pane select Web -> select ASP.NET MVC4 Web Application

Give Name as FirstMVCApp and click Ok.

New ASP.NET MVC4 Project template will be shown. Select Empty template and Razor as View engine and click Ok.

ASP.NET MVC Empty template with razor view engine

Now your basic ASP.NET MVC application has created. In next couple of steps you will learn MVC features like Controller, View. For more details check ASP.NET MVC request life cycle.

Now you will see three major folders in solution
1. Models: is responsible for maintaining data, validation of data. See how to use mvc models
2. View: is Presentation layer of your application. It displays required data, take inputs from user.
3. Controller: is responsible for users actions like selecting appropriate Action Method, validate it, interact with model and view return required response. Check for more details on ASP.NET MVC Controller, Action Method and Action Result.


Add New controller

For adding new MVC Controller, right click on Controllers folder -> Select Add -> Controller

In Add Controller window give name HomeController and from template select Empty MVC Controller -> click Add.

Add new ASP.NET MVC Controller

Now you can see HomeController.cs file under Controllers folder.


Add ActionMethod to Controller

In this step you will create couple of ActionMethod which return string or ActionResult.

ActionMethods are responsible to handle user request, validate user inputs, execute code and generate outputs. MVC Routing Engine routes user request to appropriate ActionMethod. See more details on ASP.NET MVC routing with example.

Open HomeController.cs file from Controllers folder. Add an ActionMethod with name Index. Add below code to HomeController.cs


namespace FirstMVC.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public string Index()
        {
            return "Hello, This is my first MVC application !!!";
        }       
    }
}
            

To make HomeController and Index method as default method of your website add below code in RouteConfig.cs file from App_start folder.

                
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "new",
            url: "{controller}/{action}/{name}/{id}",
            defaults: new { controller = "Home", 
                        action = "ShowDetails" }
        );

          
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{name}",
            defaults: new { controller = "Home", 
                    action = "Index", name = UrlParameter.Optional }
        );
    }
}
                
            

Now run your application. You will see the output returned from Index method is rendered to browser.


Add ActionMethod with parameters

In previous step you added a action method and returned static string. In this step you will add a ActionMethod with Parameter.

Parameters can be send as querystring however in MVC you can configure routes to use URL segments and pass it as parameter to action method.

Open HomeController.cs file and add below code. This action method accepts name as input parameter and return Hello message with value of name parameter.


public string Greet(string name)
{
    return string.Format("Hello {0},
                this is my first ASP.NET MVC application", name); 
}     
           
            

Browse to http://localhost:52937/home/greet/john. Here URL segment John is input parameter to Greet action method. It returns Hello message to John. You may use any other name instead of John. It should display below output.

ASP.NET MVC Action Method with Parameter


Action method with ASP.NET MVC View

In previous steps you created Controller and action methods which generates string as response. In this step you will create View which will work as Presentation layer to your action methods.

Open HomeController.cs file and add below action method. The action method ShowDetails takes name as parameter and display values using View by generating response as ActionResult.


public ActionResult ShowDetails(string name)
{
    ViewBag.Message = "Hello Rajan"; 
    ViewBag.YourID = "10";

    return View(); 
}
    
            

Now if you browse to ShowDetails method you will see server error as you haven't added corresponding View. Open HomeController.cs and right click on ShowDetails action method and select Add View.

From Add View dialog box keep the settings as it is and click Add. This will create Home folder under Views folder and ShowDetails.cshtml file under Home folder.

Open ShowDetails.cshtml file and add below HMTL snippet to it. It displays the value which is provided for name parameter by using ViewBag.

                
@{
    ViewBag.Title = "ShowDetails";
}

<p>
    <a href="http://dotnetmentors.com">
        <img src="http://dotnetmentors.com/images/dotnetmentors.png" 
            alt="dotnetmentors.com" /></a> 
</p>

<h2>Show Details - ASP.NET View</h2>

<p>
    <span>
        @ViewBag.Message  Your ID is  @ViewBag.YourID
    </span> 
</p>
            
            

Now run your application and browse to http://localhost:52937/home/showdetails/rajan. It generates below output.

ASP.NET MVC Action method with View and ViewBag

Download source code

Speak your mind :
Leave a comment for this article on dotnetbloogers.com