If you don’t have any idea about MVC in .NET, please see the introduction first.

Creating a basic project

Let us create a basic MVC based web application that simply displays static content.

Here are the steps:

  1. Create a new ASP.NET Web Application
    asp.net mvc1
  2. Give it the name mvctest and click OK
  3. Select MVC as the template and click OK
    asp.net mvc2
  4. Let us add a new controller named StaticController to display our static pages like about us, contact us, privacy policy etc.
    Right click on Controllers folder -> Add -> Controller…
    Select MVC 5 Controller – Empty and click Add. Enter StaticController as the name.
    asp.net mvc3
  5. There is a method named Index which is already created for you. This method represents the following URL:
    /static/index

    in your web application. For now, we will remove the Index method and add following methods ( also called actions ):

    public ActionResult ContactUs()
    {
        return View();
    }
    public ActionResult AboutUs()
    {
        return View();
    }
  6. Right click inside any method and click Add View..
    asp.net mvc4
  7. We are not going to use any layout for now, so uncheck Use a layout page option and click Add.
    asp.net mvc5
    Do the same for both the methods and following two files will be created:

    Views\Static\AboutUs.cshtml
    Views\Static\ContactUs.cshtml
  8. Here is the html for both the files:
    AboutUs.cshtml

    @{
     Layout = null;
    }
    <!DOCTYPE html>
    <html>
    <head>
     <meta name="viewport" content="width=device-width" />
     <title>AboutUs</title>
    </head>
    <body>
     <div> 
     <h1>About Us</h1>
     We are developers
     </div>
     <a href="/static/contactus">Contact Us</a>
    </body>
    </html>

    ContactUs.cshtml

    @{
     Layout = null;
    }
    <!DOCTYPE html>
    <html>
    <head>
     <meta name="viewport" content="width=device-width" />
     <title>ContactUs</title>
    </head>
    <body>
     <div> 
     <h1>Contact Us</h1>
     You can contact us anytime
     </div>
     <a href="/static/aboutus">About Us</a>
    </body>
    </html>
  9. Now run your application by clicking Debug menu -> Start Without Debugging
    You should see the default welcome page with a URL something like this:

    http://localhost:63875/

    Now navigate to following URLs:

    http://localhost:63875/static/aboutus
    http://localhost:63875/static/contactus

    You can also click the hyper-link to navigate to other URL.

Changing default URLs

By default all the URLs are of the format:

/controllername/methodname

We can provide our own URLs that maps to a particular controller’s action.

Open the following file App_Start\RouteConfig.cs file under your project and make it look like this:

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

   routes.MapRoute(
      name: "aboutus",
      url: "about-us",
      defaults: new { controller = "Static", action = "AboutUs" }
   );

   routes.MapRoute(
      name: "contactus",
      url: "contact-us",
      defaults: new { controller = "Static", action = "ContactUs" }
   );

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

Build your project by clicking on Build menu -> Build Solution. Now, we can execute following URLs to visit about us and contact us pages:

http://localhost:63875/static/aboutus
http://localhost:63875/static/contactus

ASP.NET MVC reads the file RouteConfig.cs to find if the requested URL matches any name defines in this file.

routes.MapRoute(
      name: "contactus",
      url: "contact-us",
      defaults: new { controller = "Static", action = "ContactUs" }
   );

The MapRoute method maps a custom URL to an existing controller/method.

The name parameter defines the name of the URL which could be anything we want.

The url is the URL which users are going to enter.

The defaults section specifies the controller name, the action (method) name in the controller and finally the parameters we wish to pass.

Passing data from controller to view

We can pass data from controller to view. This allows us to process the business logic in controller and the view just have to show the data.

Create a new action in the controller with following code:

public ActionResult SayHello(string name)
{
   ViewBag.name = name;

   return View();
}

You can consider ViewBag as a bucket. You can put named variables in this bucket like this:

ViewBag.variablename = valuetopass;

and it automatically gets passed to the view. The view then pulls the data out of the bucket like this:

var variablename = ViewBag.variablename;

Add the following view to SayHello action:

@{
 Layout = null;

 var name = ViewBag.name;
}

<!DOCTYPE html>

<html>
<head>
  <meta name="viewport" content="width=device-width" />
  <title>SayHello</title>
</head>
<body>
  <div> 
     Hello @name
   </div>
</body>
</html>

Add following code to the RouteConfig.cs file:

routes.MapRoute(
   name: "sayhello",
   url: "say-hello/{name}",
   defaults: new { controller = "Static", action = "SayHello" }
);

Now, build your project and visit the URL:

http://localhost:63875/say-hello/ashutosh
Passing data from view to controller

A view can also pass data to controller.

Query Strings

Query strings are used to pass data via URL or hyper-links. The syntax for passing data is:

http://sitename/url/variable1/variable2

<a href="/url/variable1/variable2">Pass data</a>

Here are two actions that demonstrates passing data in URLs. Add following lines to the RouteConfig.cs file:

routes.MapRoute(
   name: "square",
   url: "print-square/{number}",
   defaults: new { controller = "Static", action = "DoSquare" }
);

routes.MapRoute(
   name: "add",
   url: "add-numbers/{number1}/{number2}",
   defaults: new { controller = "Static", action = "AddNumbers" }
);

Add following methods to the StaticController:

public ActionResult DoSquare(int number)
{
   return Content((number * number).ToString());
}
public ActionResult AddNumbers(int number1, int number2)
{
   return Content((number1 + number2).ToString());
}

Instead of moving to a view page, this time we just wanted to return a text result. For this, we replaced return View() with return Content().

Now build the project and navigate to following URLs:

http://localhost:63875/print-square/5
http://localhost:63875/add-numbers/5/6

Submitting Forms

We can submit our html forms to a controller as well. Here is an example:

Add following lines to the RouteConfig.cs file:

routes.MapRoute(
   name: "login",
   url: "login",
   defaults: new { controller = "Static", action = "Login" }
);

routes.MapRoute(
   name: "dologin",
   url: "do-login",
   defaults: new { controller = "Static", action = "DoLogin" }
);

routes.MapRoute(
   name: "success",
   url: "success",
   defaults: new { controller = "Static", action = "LoginSuccess" }
);

routes.MapRoute(
   name: "failure",
   url: "failure",
   defaults: new { controller = "Static", action = "LoginFailed" }
);

Now add following code to our static controller:

public ActionResult Login()
{
   return View();
}

[HttpPost]
public ActionResult DoLogin(string email, string password)
{
   string correctEmail = "a@b.com";
   string correctPassword = "password";

   if (email.Equals(correctEmail) && password.Equals(correctPassword))
      return Redirect("success");
   else
      return Redirect("failure");
}

public ActionResult LoginSuccess()
{
    return View();
}
public ActionResult LoginFailed()
{
    return View();
}

Now create views for Login, LoginSuccess and LoginFailed. Here is the html for views:

Views\Static\Login.cshtml

@{
 Layout = null;
}
<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width" />
   <title>Login</title>
</head>
<body>

<form action="/do-login" method="post">
   Email: <input type="email" name="email"/><br/><br/>
   Password: <input type="password" name="password" /><br /><br />
   <input type="submit" value="Check Login"/>
</form>

</body>
</html>

**Note: The fields must have names email and password as they must match the method parameters DoLogin(string email, string password)

Views\Static\LoginSuccess.cshtml

@{
 Layout = null;
}

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width" />
   <title>Login Successful</title>
</head>
<body>
   <div> 
      <h1>Your login was successfull</h1>
   </div>
</body>
</html>

Views\Static\LoginFailed.cshtml

@{
 Layout = null;
}

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width" />
   <title>Login Failed</title>
</head>
<body>
   <div> 
       <h1>Your login was wrong</h1>
   </div>
</body>
</html>

Now visit the URL:

http://localhost:63875/login