Before we talk about JQuery and ASP.Net MVC let's take an overview about both of them.
Here we go,
1- What is MVC Framework?
Model View Controller Model is a design pattern that allows separation of concerns. As the framework consists of 3 components:
a. Model: .is the component responsible for maintaining data.
b. View: is the component responsible for displaying the user interface.
c. Controller: is the component responsible for handling all the user interaction and all the manipulation of the model and passing the data to the view to display it.
For more information there is a lot of resources out there.
2- What is ASP.Net MVC?
ASP.Net now supports the MVC Framework, as part of the CTP Preview of an "ASP.NET 3.5 Extensions" for more information about what's in that extension refer to Scott Gu's blog .
In ASP.Net MVC the controller handles all the interaction with user collects the information and manipulates the model data and then renders the appropriate view. So it allows a great deal of separation of concerns and it makes it a lot easier to test your application without even building the user interface. And it also gives you the control over the URL in a neat way.
For more information about ASP.Net MVC Scott Gu has made a pretty cool series of tutorial in his blog, Check it out here.
3- What is JQuery?
jQuery is an amazing JavaScript library that makes it easy to create wonderful web effects in just a few lines of code. As the website says:”
“jQuery is a JavaScript library that takes this motto to heart: Writing JavaScript code should be fun. jQuery achieves this goal by taking common, repetitive, tasks, stripping out all the unnecessary markup, and leaving them short, smart and understandable.”
4- How JQuery works with Asp.net MVC???
Okay, as you already know there is no post back in ASP.Net MVC. And so there is no server controls J What about ASP.NET AJAX UpdatePanels? Scott Gu mentions this in his comments:
UpdatePanel does use post back, so you won't use that control directly within a MVC based view. But there will be a control (and optional helper method) with capabilities very similar to it. It will invoke an action on a controller and allow you to incrementally update a portion of HTML really easily. It will enable you to use the ASP.NET AJAX libraries really easily.
Well why don't we try to do that with Jquery and ASP.Net MVC .,
Okay lets start by downloading CTP Preview of an "ASP.NET 3.5 Extensions"
And the latest JQuery, In this tutorial I'll be using the northwind database you can download it from here, Now let's try to create an update panel with jquery.
Okay so here is what we want to do:
1- List all the categories in the categories table.
2- When we click on any category we want to go to the server and bring back all the products inside that category without post back ofcourse.
So let's see how we can do that,
1- After you installed the CTP Preview, Create a new project and you will have a new project type called "ASP.NET MVC Web Application" Choose it and name the project "MVCJQueryMagic".
2- Now let's add our model, Right Click the model folder and add a new item and choose "Linq To SQL", and then we will use the server explorer and drag the categories & Products tables and the ORM designer will infer the relations between the tables. And name it "Northwind.dbml".
3- Now after creating our model as we all know our controller is the only thing that is allowed to manipulate the model's data and it's good practice and recommended that you keep your controller code short, So now we will create some helper methods in our "DataContext" that was created by our ORM Designer that will help us in both keeping our controller code short and in retrieving data from our model.
a- First create a partial class and name it "NorthwindDataContext":
b- We will create two methods the first one to get all the categories from the categories table. The second one will take a category id as a parameter and return a list of products for that category. In this code I use LINQ to retrieve a list of categories in the "GetCategories" method and used lambda expressions in the "GetProducts" method to get a list of products for a specific category.
In this code I use LINQ to retrieve a list of categories in the "GetCategories" method and used lambda expressions in the "GetProducts" method to get a list of products for a specific category.
At this point we are done with our model. Let's move on to the controller.
1- Right Click On the controller folder and add a new item and choose "MVC Controller" and name it "ProductsController".
2- In our case we will have two action methods the first one is to handles the requests asking for the categories, and the second one is to handle our AJAX request to get all products for a specific category.
In the previous screen:
All I do here is using our helper methods to get the data required to call our Renderview Method. I also created a class named "ProductsViewData" to send the list of products along with the category's name. For more information about passing view data to views refer to Scott Gu's Blog here.
Now, Our UI is ready to be created, let's dig in.
If you looked at the controller class you will see that we need to create two views but again if you remember at first we said that what we are going to do is a page with a list of categories and once you click any category all the products inside that category will appear in the same page " AJAX Call ", That's a little bit confusing, Isn't it?!!!!
Well nooooo, it's not. Here is what's going to happen:
1- Our Ajax call will call an action method "GetProducts" asking it to get all the products for the category specified by the id.
2- The "GetProducts" Action method will get the products data and pass it to the view responsible for rendering these data.
3- Then it passes the rendered page back as a response for our Ajax call.
4- We then take this page and by using JQuery we can attach it to our Category List Page.
So if you think about it the second view is considered a partial view.
Now let's create our views:
1- Let's create our "Products" Folder inside our Views Folder (That's the default place which the mvc framework will be looking for the views in the products controller).
2- Let's add our partial view, Right Click on the "Products" folder that we just created and add new item and choose "MVC View Page" and name it "Partial_Products".
3- Remove everything from the page and leave the page tag only because as we mentioned this is a partial view page all it does is rendering the products list.
4- Add this code to the page.
This code first writes the Category name as a title and then creates an unordered list with the products for that category.
Now lets move on to the fun part, creating the view which will contain our Ajax call.
1- Let's add our view, Right Click on the "Products" folder that we just created and add new item and choose "MVC View Content Page" just use our master page (you can create a "MVC View Page " without using the master page it's up to you)and name it "CategoriesView".
2- Let's create the code to render our list of categories as links which when clicked will invoke a java script function.
At the bottom in the previous screen:
we've created an empty div and set its display to none to be invisible, we will be using this div to show our products retrieved from the Ajax call.
3- Now let's write our java script function which will make the ajax call to the server to get our products back and make sure you have included the jQuery Library.
In the above screen:
1- We created a function with the same name that we call from our links.
2- var productsContainer = $("#divProducts");
we get a refrence to our div we created earlier using
JQuery Syntax ( $ -> is shortcut for "jQuery" and # is used to select element by id).
3- var url = '/Products/GetProducts?category='+ categoryName;
Here I compose the url to which we are going to make our ajax call to get our products.
4- $.get(url,function(data)
{
productsContainer.fadeIn('slow');
productsContainer.html(data);
})
The ($.get ) JQuery syntax is used to make a jax call to the server and as you can see it takes to parameter
1- The url that it's going to make the call to
2- The function to pass the data returned from the call.
In the function we show the div (the fadIn() function does a littel fad in animation just to give a good look) and set the inner html of our empty div to display the returned data from the server.
.
For our final step to let the mvc framework where to go when our generated url is requested we need to define A Route in the "Global.asax" File.
No comments:
Post a Comment