06/04/2012

$.post and $.get in MVC Razor & JQuery

CodeProject
In this post we will see when to use and How to use ajax calls in MVC Razor using JQuery.

When i am trying to create a POC for combination of entity framework and a MVC Application, i came across this requirement which made me to use $.post() and $.get().

Now, people very easily say, $.post() for posting data and $.get() for getting data using ajax call. Great!
But its not that simple as saying it. We need to decide what has to be used in combination of these ajax calls.

While writing application, i need to create a cascading dropdown. But its not simply mapping the options. I need to fetch the data from Data base using EF4.0.

Let me illustrate that for better understanding.

Step 1: I created a partial view with name "OrderCatalog". Now, i am rendering it on to Main view.
But, there are different ways of rendering Partial views.
1. @Html.Render()
2. @Html.RenderPartial()
3. @Html.Action()
First 2 options are out of question as i am using entirely different Model than main view. Now i used 3rd option.

<div id="divCatalog">
@{Html.RenderAction("OrderCatalog");}
</div>

Step 2: Designing the OderCatalog.cshtml. Here i have two drop downs "Category", "Product".

Step 3: Now, when a item was selected in Category dropdown, i need to post that data and get the required data from Database using EF. For that i use $.post() to call a action method by posting the data. And all this will happen without postback.Action Method:

If you observe the part of $.post() highlighted is way of passing the parameters to the action method. First part is parameter name in action method, and second part is script variable we have. With this, once the option is selected in Category dropdown, the value will be posted to Action method "GetProducts" and the list of products that need to be displayed in Products were parsed as JSON and sent back by action method.

Wonderful !

Whats the out put? Nothing. lets see why?

Step 4:
Once after completion of Post method, the function you wrote inside $.post() will be called, and the parameter "data" is nothing but the JSON response send by Action method. Now, we need to handle this data carefully. Now see how i modified my call back function to accommodate the request.Script:

Now, we have seen $.post(). Now lets see $.get().
$.get() is now way different from $.post(), except it has nothing to post from client side. So it is used to call a action method and get the response and do whatever you want to do with the response.
If you observe carefully there is no parameter part in $.get().For example: