-->

06/04/2012

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


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".
    <fieldset>        
        <legend>OrderCatalog</legend>
         <table width="80%">
            <tr>
                <td>
                    <div class="editor-label" id="divCategory">
                    Select Category:
                    </div>
                    <div class="editor-field">
                    @Html.DropDownList("Category", new SelectList(Model.categories, "CategoryID", "CategoryDesc"))       
                    </div>        
                </td>
                <td>
                    <div id="divProduct" style="display:none">
                        <div class="editor-label">
                        Select Product:
                        </div>
                        <div class="editor-field">                        
                        @Html.DropDownList("Product", new SelectList(Enumerable.Empty<SelectListItem>(), "CategoryID", "CategoryDesc"))                        
                        </div>                                            
                    </div>
                </td>
            </tr>
        </table>
    </fieldset>
This will give a look of this.
Yes, Products will not be seen until catrgory si selected. The options inside the Category dropdown were populated using the action method to call this specific
public ActionResult OrderCatalog()
        {
            EntityMVCDatabaseEntities dbcontext = new EntityMVCDatabaseEntities();
            var _categories = dbcontext.Categories.ToList();
            ordCatMod.categories = Models.Category.MapCategorytoModel(_categories);
            return PartialView("OrderCatalog", ordCatMod);
        }

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:
[HttpPost]
        public ActionResult GetProducts(string categoryId)
        {
            int catIdInt;
            if (int.TryParse(categoryId, out catIdInt))
            {
                EntityMVCDatabaseEntities dbcontext = new EntityMVCDatabaseEntities();
                var _products = dbcontext.Products.Where(p => p.CategoryID == catIdInt).ToList();
                ordCatMod.products = Models.Product.MapProductToModel(_products);
                ordMaster._orderCatalogModel = ordCatMod;
                return Json(ordCatMod.products.AsEnumerable(), JsonRequestBehavior.AllowGet);
            }
            return Json(false);            
        }
Script for calling that Action Method:
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("#Category").change(function () {
            var divProd = $("#divProduct");
            var SelCat = $("#Category").val();
            if (SelCat != 0) {
                var url = '@Url.Action("GetProducts", "Home")';
                $.post(url, { categoryId: SelCat },
                function (data) {
                });
                divProd.show();

            }
            else {
                divProd.hide();
            }
        });
    });   
</script>
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:
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("#Category").change(function () {
            var divProd = $("#divProduct");
            var SelCat = $("#Category").val();
            if (SelCat != 0) {
                var url = '@Url.Action("GetProducts", "Home")';
                $.post(url, { categoryId: SelCat },
                function (data) {                    
                    var productDropdown = $("#Product");
                    productDropdown.empty();
                    for (var i = 0; i < data.length; i++) {
                    productDropdown.append('<option value?+data[i].productid+?="">'+data[i].ProductName+'</option>');}
                });
                divProd.show();
            }
            else {
                divProd.hide();
            }
        });
    });
</script>
Now, see the output:

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:
function RefreshView() {        
        var url='@Url.Action("OrderCatalog", "Home")';
        $.get(url, function (data) {            
            //Do whatever u waht with response "Data"
         });
    }

Hope i made myself clear.
Is it helpful for you? Kindly let me know your comments / Questions.

No comments:

Post a Comment