How does our controller retrieve data from the client? By client data we mean URL parameters and data posted by controls on our page.
There are 3 ways to pass parameters to the controller:
public class EmployeeDetail : Controller { public void Run(int id, string action) { Employee employee = new Employee(id); if (action == "delete") { employee.Delete(); } else { ViewData["CurrentEmployee"] = employee; } } }
In the example above we defined two parameters "id" and "action". These parameters are retrieved from the URL that was requested.
For example, when the URL is http://www.yoursite.com/emplyeedetail.ashx?id=5&action=delete , the "id" and "action" parameters will be passed to the Run() method. If a parameter is not specified, null is passed (when the type of the parameter is not nullable, the default value for the specific data type will passed)
Instance fields can also be mapped to parameters by decorating them with the [Get], [Post] or [GetOrPost] attribute:
public class EmployeeDetail : Controller { [Get("id")] private int _id; public void Run(string action) { Employee employee = new Employee(_id); if (action == "delete") { employee.Delete(); } else { ViewData["CurrentEmployee"] = employee; } } }
In the above example, the _id field is mapped to the id parameter
It is also possible to retrieve parameters and form data by using the GetData and PostData objects:
public class EmployeeDetail : Controller { public void Run() { int id = Parameters.Get<int>("id"); // uses the Get() method (generic version) string action = Parameters["action"]; // uses the indexer Employee employee = new Employee(id); if (action == "delete") { employee.Delete(); } else { ViewData["CurrentEmployee"] = employee; } } }
>> Next: Part 5