Saturday, November 7, 2009

MVC Anatomy

In a previous post we saw how to create a Hello World MVC application.
Now we're going to perform an anatomy to this application to know what each part of the application exactly means.

First: Where is the Model, the View and the Controller ?
MVC Controller:
In tradotional asp.net the url you type corresponds to a page on the server, so when you request yoursite/abou.aspx there must be a page named about.aspx or a 404- page not found error is thrown.

In MVC it's different, there is no correspondance between the url you type and the pages that exist in the application. rather the url corresponds to a controller action than a page on the server.

The Controller is responsible for the way the user interacts with the application.
it manages the flow control logic of the application. It determines what response to make when the user makes a browser request.

The Controller is a C# class. Our Hello World application contains a controller class named HomeController.cs, It contains only one function named:public string Index()

public string Index()

{
return "Hello World";

}
this function is called when the user types URL /Home/Index in the browser cause as we said the controller functions respond to a user request.
Final thing to note that any public method contained in a controller is exposed as a controller action, meaning that it can be invoked by any user by typing it's name in the browser.
so if you have a function declared public as the following:

public void SomeFunction()







{



// Some Code



}

Any user can call this function by typing URL/Home/SomeFunction so be careful when declaring public functions in Controllers.

MVC View:
The view is equivalent to a page in t ASP.NET. It contains HTML markup that appears on the browser.
so for example if you want to create a page called demo , in Views folder create a subfolder named demo then in this subfolder create an aspx called Index.
then go to the Controllers folder and create a new controller with the name

DemoController.cs

in DemoController.cs add the following code


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

so when the user types url/demo the demo page is displayed
Notice that you must create the controller class in this form [ViewName]Controller.cs
MVC Model:
The MVC Model Contains you business logic, Validation logic or database access logic.
since that the Hello World application is not that complicated, there are no models in this application
Conclusion:
The view contains the logic for the interface, the Controller contains the logic for redirecting the user correctly to pages and respond to the user requests. And the Model contains the business or database access logic.
The Controller should contain minimal amount of code to handle user requests only.
If the Controller contains large bulks of code, consider removing some of them to a Model class in the Models folder

No comments:

Post a Comment