Adding a Controller and View Page in ASP.NET MVC 5

In this chapter, you will learn:
1. How to add Controllers in ASP.NET MVC 5 Project?
2. How to add a View Page for Controllers in MVC 5?

In the previous chapter, you learned basics of Controller. However, the theory is not as important as practical is. In this chapter, I have added a very simple controller and their view page to make you understand how controller and view page works together.

1. Go to Solution Explorer and Right click on Controllers folder Add Controller
Add Controller
2. Select MVC 5 Controller – Empty and click on Add button
Empty MVC Controller
3. Give Controller Name to ItemController. "Controller" suffix must be added in controller name. Click Add button to add controller.
4. Your Item Controller will look like this.
Item Controller
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CompShop.Controllers
{
    public class ItemController : Controller
    {
        // GET: Item
        public ActionResult Index()
        {
            return View();
        }
    }
}
  Explanation:
This controller will execute when user browse following url:

http://localhost:1233/Item/index

In the above link, Item is controller and Index is action method.

When user click on the link, it will search for ItemController with Index() Action method. Controllers keeps action method that gets executed when user needs them. There must be a ViewPage Index.cshtml in Item Folder, otherwise you will get error message.

Adding a ViewPage for Index method

1. Right click on Index Action Method and select Add View
Add View
2. Select option as picture below and click Add button to add view page.
Add View
3. Your Index view page is added. You can see here.
Item Let's pass a message from controller to view page
1. Add following codes in ItemController.cs file.
using System.Web.Mvc;

namespace CompShop.Controllers
{
    public class ItemController : Controller
    {
        // GET: Item
        public ActionResult Index()
        {
            ViewBag.ItemList = "Computer Shop Item List Page";
            return View();
        }
    }
}
2. Add Following code in Item Index.cshtml file.
<h1>@ViewBag.ItemList</h1>
3. Press F5 to run your project and go to following link:
http://localhost:1233/Item/Index

4. Output
Output

Summary

In this chapter, you seen that there is an ActionResult Index() method. You must be thinking about ActionResult. In this next chapter, we will learn all ActionResult method with the help of programming example.

 

Share your thought