Click here to Skip to main content
Click here to Skip to main content

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

By , 24 Jul 2012
Rate this:
Please Sign up or sign in to vote.

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

PratapReddyP
Web Developer
India India
I am an Aspiring Architect, having expertise in Design and Development. Good knowledge on TDD and DDD Approaches. Well versed with Agile methodology. Strong at Sharepoint, C# , Asp.Net, MVC, MVC Razor, WCF, Entity Framework, SQL, BI Tools.

Comments and Discussions

 
GeneralMy vote of 4 Pinmemberdheeraj10014-Nov-13 21:57 
GeneralThanks! Pinmemberjohan_vw13-Nov-13 21:49 
QuestionExcellent Article PinmemberMazher Ul Haq24-Jun-13 23:44 
GeneralGreat PinmemberMartins Carlos26-May-13 23:35 
GeneralMy vote of 5 PinmemberMAXIMILLIAN WIGGS15-May-13 17:18 
GeneralMy vote of 5 Pinmembermanoj kumar choubey9-Aug-12 20:18 
GeneralMy vote of 1 Pinmemberalec.whittington28-Jul-12 3:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 24 Jul 2012
Article Copyright 2012 by PratapReddyP
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid