Monday, May 21, 2018

ASP.NET MVC - Ajax Get Method not hitting the ASP.NET MVC Controllers

I have recently faced this issue, when I tried to load partial view by calling Ajax Get method (code as below). First time it called ASP.NET MVC controller method but second time it did not hit controller.

Here is source code 

HTML View Code:


<html>

<body>

    <div id="contentDivID">      

    </div>

    <div><input id="btnLoad" type="button" value="Load" class="btn-info"  onclick="AddToCart();"/></div> 

</body>

</html>


Java Script:


<script type="text/javascript">

    function AddToCart() {

        var theDiv = document.getElementById("contentDivID");

        $("#btnLoad").text("Loading ...");

        $.ajax({

            url: 'http://../LoadInfo',                     

            success: function (results) {

                var div2 = document.createElement("DIV");

                div2.innerHTML = results;

                theDiv.appendChild(div2)

                $("#btnLoad").text("Load");

            },

        });

    }

</script>


MVC Controller:


        public ActionResult LoadInfo()

        {

            return PartialView("_Info", infos);

        }




After initial analysis, I realized that it was due to browser cache response and the browser caches the response for request and if in the second time, you send similar request the browser, browser will not forward request to server and it returns the cached response to server.


We have two ways to stop browser caching feature.


1.   Decorate the action method not to cache the response


[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]

public ActionResult LoadInfo()

        {

            return PartialView("_Info", infos);

        }

2.      2.  Include cache = false attribute


$.ajax({

cache :  false,

            url: 'http://../LoadInfo'

 Other ASP.NET MVC related topics 
Thanks for visiting!! 

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...