Background
ASP.NET MVC is the architectural pattern based on ASP.NET framework which provides a clean and elegant way of developing Web application. Before we can understand why MVC is in vogue we need to understand some limitation of Web forms first.
ASP.NET MVC architecture.
- ViewState: This is the heart of ASP.NET when it comes to the ability of ASP.NET to provide stateful abstraction over stateless HTTP protocol. But with great power comes great responsibility If the ViewState is not managed properly then this would increase the size of the rendered web page a lot and this causing extra load.
- Generated HTML: Server side controls are another strong selling points of web forms. They facilitate rapid application development without worrying too much about the client side HTML code. But since the use of client side technologies are increasing (javascript, jQuery etc.), the less control over generated markup is becoming bit of a problem.
- Urls: In ASP.NET web forms the request URL points to physical files and the structure of the URL is not SEO friendly. Also, now is the time when URL structure is very important and clean URLs and control over URLs is very much desired.
- Code Behind: Code behind model, in my opinion, is the best part of ASP.NET. It provides clear separation of concern. From a developers perspective having the code behind file provides a great way to write the server side logic without having to write code between the HTML markup.
- Page Life Cycle: Although code behind model provides a great way for providing separation of concern, the page life cycle is little complex and should be fully understood. If a developer fails to understand the page lide cycle then there might be some unforeseen and undesired issues in the final application.
- Test Driven Development support: Now is the time of being agile. When we follow agile methodology (scrum specifically), it id very important to define the "Done" in scrum. TDD helps in this. If all our test cases are passed then we can be sure that the "Done" is done. ASP.NET does not provide native support for TDD because it is kind of difficult to imitate the HTTP request and HTTP context.
Model
: These are the classes that contain data. They can practically be any class that can be instantiated and can provide some data. These can be entity framework generated entities, collection, generics or even generic collections too.Controllers
: These are the classes that will be invoked on user requests. The main tasks of these are to generate the model class object, pass them to some view and tell the view to generate markup and render it on user browser.Views
: These are simple pages containing HTML and C# code that will use the server side object i.e. the model to extract the data, tailor the HTML markup and then render it to the client browser.
Let us go ahead and create a new MVC 3 Web Application.
Upon asked, let us select the Razor View Engine.
Now this template comes with a lot of predefined Controllers, models and view. Let us delete all this and just have three Folders named Models, Views And Controllers in this application.
Now let us start by defining our own route in the
global.asax
. Now the Controller that we want to access by default will be DemoController
. We want the Index action of this controller to execute by default. We will also pass an ID which, if present will also be displayed on the page. So the route defined for this in the global.asax
will look like:
Hide Copy Code
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Demo", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
And now Let us add a Controller named Demo to this application. This can be done by right clicking the controller's folder and selecting Add Controller. Name this Controller as
DemoController
.
Now this controller comes with a default action Index. This action will be called if no action is specified for this controller. Let us show a simple message if this controller is invoked. We will use
ViewBag
for this. Viewbag
is an object that is accessible in the View page and it should be populated in the Controller.
Hide Copy Code
public ActionResult Index()
{
ViewBag.UsageSample =
@"Please Use the Url 'Demo/Test' or 'Demo/Test/1' to see the Book Details";
return View();
}
Note: We are not taking about the data transfer techniques like
ViewBag
, ViewData
and TempData
in this article. that topic requires some detailed discussion. We will perhaps discuss them later.
Now this code will simply put a string in the view bag and call the View. The return statement will expect a view named index present in a folder named Demo. We don't have that right now so let us create this view by right clicking the method name as:
This will then ask for more options for the view we need to add. For now lets not select any other option and just create the view.
Now in the view we will write the logic of extracting the data from
ViewBag
and showing it on the page.
Hide Copy Code
<div>
@ViewBag.UsageSample;
</div>
And now if we try to run this application:
And so we have seen how the controller gets invoked from the the user request and then controller passes some data to the view and the view renders it after processing. But we have not yet added any model to it. Let us add a simple Model in this application. Let us define a simple model for a
Book
class in the models folder. We will then see how we can use instantiate this model and use this in our View.
Hide Copy Code
public class Book
{
public int ID { get; set; }
public string BookName { get; set; }
public string AuthorName { get; set; }
public string ISBN { get; set; }
}
Now let as ad an action called Test in this
DemoController
and create an object of this Book
Model. Once the object is created we need to pass this object in the view as:
Hide Copy Code
public ActionResult Test()
{
Book book = new Book
{
ID = 1,
BookName = "Design Pattern by GoF",
AuthorName = "GoF",
ISBN = "NA"
};
return View(book);
}
the above code will create the model and pass it to the view. Now lets create a view that is capable of extracting the data from this model. This can be done by creating a strongly typed view as:
I have also chosen the scaffold template as "
Details
" so that all the boilerplate code in the view page to display these details is already generated.
And now we run the code we can see the details of the book which were extracted from the Model which was created in the controller, which was executed on parsing user's request URL.
And thus we have our very first MVC 3.0 application with razor view engine working.
No comments:
Post a Comment