Funny bug in ASP.NET MVC While creating a new project

June 6, 2008 at 7:36 am | Posted in ASP.Net MVC | Leave a comment
Tags:

While i was playing with ASP.NET MVC CTP3 i met this funny bug while creating a new MVC project in visual studio 2008:

1- Create a new mvc project and choose to have a test project.

2- In the project name put “-”.

3- Hit ok, The project will be created succefully, That’s great but try to build.

Apperantly the “-” has been replaced With “_” in the namespace name but the odd thing they didn’t use the right name in the test project :)

And here is the bug:

Beckham

ASP.NET MVC Preview 2

March 15, 2008 at 7:12 am | Posted in ASP.Net MVC, Java Script, jQuery | 1 Comment

ASP.NET MVC Preview 2 is released and you can download it from here.

In this CTP, A lot of changes happened in the MVC framework such as:

1- When you define a controller action method you don’t have to put the [ControllerAction] all you have to do is to define the method as public and it will be part of the contract, Okay but what if I wanted to define a non action method, well now you have to put an attribute J [NonAction].

2- Another thing is the {*catchall} The new * which allows you pass anything from the * to the end of the URL as a parameter for the action. And this is actually what I’m going to talk about in this post. But you can find a lot of stuff about the ASP.NET MVC Framework Preview 2 in Scott Hanselman Videos here.

In my previous post I bloged about ASP.NET MVC & JQuery, I was calling an action method which takes as a parameter the name of the category (In the Northwind database) to get the products for that category.

Well, the thing is some of the categories name contains “/” which as you already know is used in the URL, so it didn’t work. I overcome this issue by using Query String to pass in the parameter to the action method like that:

var url = ‘/Products/GetProducts?category=’+ categoryName;

But now with the new {*catchall} route rule it can be done.

routes.Add(new Route( “Products/GetProducts/ {*category}”,new MvcRouteHandler())

{
Defaults = new RouteValueDictionary (new

{

controller = “Products”,

action = “GetProducts”

}),

});

As you can see I used the {*category} not {*catchall} so catchall is not a keyword the * is the important part. But the important thing is whatever name you put after the {*} you must use the same name for the action method parameter.

For example, in the previous snippet I used:

“Products/GetProducts/{*category}

So in my Get Products action method I must pass in a category parameter like that:

public void GetProducts(string category)

{

}

The full source is attached.

P.S: To convert an MVC Application from Preview 1 to Preview 2 there is a lot of stuff and I mean “a lot” that you will have to change to get your application up and running and most of the changes will not be in your code. So if your application is a small one my advice is that create  a new application and just copy & paste your code in to it and now the changes that you will have to make is in your code J

But if your application big and hard to just copy & paste just follow the steps the release notes here.

Beckham

ASP.Net MVC & JQuery Magic

March 14, 2008 at 8:36 am | Posted in ASP.Net MVC, Java Script, jQuery, Tips & Tricks | 1 Comment
Tags:

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:

MVC

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”.

MVC Project

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”.

MVC

MVC

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”:

MVC

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.


MVC

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”.

MVC

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.

MVC

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).

MVC

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”.

MVC

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.

MVC

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”.

MVC

2- Let’s create the code to render our list of categories as links which when clicked will invoke a java script function.

MVC

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.

MVC

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.

MVC

Well that’s it we have our update panel up and  working. You can download the source code from attachment.

P.S: an updated version with MVC Preview 2 available here.

Beckham

Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.

Follow

Get every new post delivered to your Inbox.