Wednesday, September 17, 2014

ASP.NET 4 MVC 4: How Controllers Work

ASPNET 4 MVC 4 How Controllers Work

Professional ASP.NET MVC 4 (111834846X) cover image

This tutorial is based on “Chapter 2 Controls” of the book

Professional ASP.NET MVC 4

Jon Galloway, Phil Haack, Brad Wilson, K. Scott Allen, Scott Hanselman
ISBN: 978-1-118-34846-8
Paperback
504 pages
October 2012

STEPS

1) Edit HomeController.cs

2) Observe the output

Stop the project execution.

3) Add New Controller

3-1) In Solution Explorer, right-click Controllers item, select Add/Controller…
3-2) Specify Controller Name and Template.
3-3) New controller, StoreController.cs, has been created with basic codes.
Notice line no. 14-17.

4) Edit New Controller

4-1) Replace the codes above with the following codes.
        public string Index()
        {
            return "Hello from Store.Index()";
        }
4-2) Outcome
4-3) Insert some codes on the next line
        //
        // GET: /Store/Browse
        public string Browse()
        {
            return "Hello from Store.Browse()";
        }
        //
        // GET: /Store/Details
        public string Details()
        {
            return "Hello from Store.Details()";
        }

5) Adding Parameters

5-1) Using Query String Value.
Replace the Browse method (in Step 4-3)
        //
        // GET: /Store/Browse?genre=Disco
        public string Browse(string genre)
        {
            string message =
            HttpUtility.HtmlEncode("Store.Browse, Genre = " + genre);
            return message;
        }
5-2) Using ID Value
//
// GET: /Store/Details/5
public string Details(int id)
{
string message = "Store.Details, ID = " + id;
return message;
}

No comments:

Post a Comment