Fetch additional information via Ajax request when button is clicked within MVC 4

I am building a feature to display 6 records in an HTML table with a button labeled Load More. The goal is for each click of the button to retrieve another set of 6 records. Here's what I have tried so far:

Within the Controller

[HttpGet]
private JsonResult GetTweetData(int count)
{
    try
    {
        using (var context = new DbContext())
        {
            var totalRecords = context.ObjTwitterDatas.Count();
            var startFrom = 6 * count; // By default, it starts from 0 and retrieves 6 records at a time
            var query = context.ObjTwitterDatas.Where(x => x.TwitterDataId >= startFrom && x.TwitterDataId <= totalRecords).Take(6);
            var dataContainer = query.ToList();
            return Json(dataContainer, JsonRequestBehavior.AllowGet);
        }
    }
    catch (Exception e)
    {
       return Json(new { success = false, ex = e.Message }, JsonRequestBehavior.AllowGet);
    }
}

Implementing Ajax call in the ready method

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: '@Url.Action("GetTweetData" ,"Home")',
            contentType: "application/json; charset=utf-8",
            data: { count: 0}, // The count will be updated dynamically to load the next 6 records on button click
            dataType: "json",
            success: function (data) {
               if(data.length > 0){
                    // Append Data to Table
                }
                else{
                    alert('No More Records to Load')
                }
            },
            error: function () {
                alert("Error");
            }
        });
    });
     $('#Btn-More').on("click", function () {
         // Need assistance with properly fetching the next set of 6 records eg. 7-12
    });
</script>

Answer №1

After trying out the code below, it successfully worked for me

[HttpGet]
    public JsonResult GetTweetData(int count)
    {
        try
        {
            using (var context = new DbContext())
            {
                var count = context.ObjTwitterDatas.Count();
                var countData = count - (6 * tweetcount); //it will exclude the previous 6 records

                var dataContainer = dtls.Where(x => x.TwitterDataId <= countData && x.TwitterDataId >= 1).OrderByDescending(x => x.TwitterDataId);
                var dataContainer2 = dataContainer.Take(6).ToList();
                return Json(dataContainer2, JsonRequestBehavior.AllowGet);
            }
        }
        catch (Exception e)
        {
           return Json(new { success = false, ex = e.Message }, JsonRequestBehavior.AllowGet);
        }
    }

Using Ajax call within ready method

<script type="text/javascript">
 var countTweet = 0;
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: '@Url.Action("GetTweetData" ,"Home")',
            contentType: "application/json; charset=utf-8",
            data: { count: countTweet },
            dataType: "json",
            success: function (data) {
               if(data.length>0){
                    countTweet = countTweet + 1; // This will exclude the previous 6 records
                    //Appending Data in Table
                }
                else{
                    alert('No More Records to Load')
                }
            },
            error: function () {
                alert("Error");
            }
        });
    });
     $('#Btn-More').on("click", function () {
         // Calling same method to fetch but not able to make properly to get more 6 record eg. 7-12
    });
</script>

Answer №2

After some research, I discovered the solution I was looking for on this site. The solution is implemented using MVC and utilizes partial view to fetch additional data.

Learn More about Loading Additional Data

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the masterRequest URL within a fragment controller

Upon clicking a button, I have implemented a method that is triggered by an Ajax request. /** * @param Request $request * * @Route("/add", name="rapid_access_add", options={"expose"=true}) * @Method({"GET"}) * * @return Response */ public function ...

What is the best way to create a toggle function for a specific span element that switches between showing more or

I came up with this solution: $(".morelink").click(function(){ $(this).siblings(".DescMore").show(); $(this).hide(); }); After tweaking the code, only the content related to the clicked link will be shown. Here's what I did: Here is the mod ...

Error: The jQuery Class is returning an undefined value

I have been working on creating a basic AJAX request class in jQuery. However, I've encountered an issue with the 'process' function where I can get the response from the variable 'response'. When I return 'response', it ...

Ways to create distance between repeated cards in a loop. My method involves utilizing ajax, jquery, and bootstrap

view image description here What is the best way to create some space between these closely aligned cards? .done((todos) => { todos.forEach(el => { console.log(el) $("#todo-list").append(` <d ...

Unsuccessful attempt at testing RequireJS in a straightforward manner

As a beginner in RequireJS, I am currently experimenting to gain some experience. My goal is to make require load basic Angular first and then manually bring in Angular UI Bootstrap. However, I am encountering an issue where UI Bootstrap complains that ang ...

Sending dynamic boolean model property via AJAX dynamically

I am facing an issue while passing a property from my model to an AJAX form. The boolean value is resolving as "true/false" and causing problems in the process. $.ajax({ url: '/Projects/SearchTable2', type: "GET", data: { sub ...

Interacting with jQuery mouse events on elements below the dragged image

I'm attempting to create a drag-and-drop feature for images using jQuery. While dragging, I generate a thumbnail image that follows the mouse cursor. However, this is causing issues with detecting mouseenter and mouseleave events on the drop target pa ...

disabling a submit button

I am new to coding and need help disabling a button on document load. Can someone assist me with this? Here is my current code snippet: $(document).ready(function() { setTimeout("check_user()", 250); }); Your guidance is greatly appreciated! ...

Clicking on the radio button will automatically update the <span> element

I have a DIV that contains a list of radio buttons and a 'selected search' area (a <span>). When the 'selected search' area is clicked, a drop-down layer appears with the DIV containing the radio buttons. Upon selecting a radio bu ...

Refreshing and reloading within the same jQuery function

My PHP application involves the use of 2 PHP files. chart.php - This page includes a Google chart. <div id="chart_div" style="height:100%;width:100%"> </div> <script type="text/javascript"> google.charts.load('current', ...

Incorporating Angular into the script code of the extension content

I am looking to customize text fields on a website using a chrome-extension. However, the website is built with Angular, so I need to modify the text fields using Angular code. To incorporate Angular in my extension's scope, I am attempting to declar ...

Guidance on utilizing jQuery to display values depending on a dropdown selection

This code snippet displays movie data from a JSON variable in a dropdown list based on the selected city. It also needs to show the movie name and theaters list when a user selects a movie, along with the theater dropdown remaining unchanged. Here is my H ...

activated by selecting a radio button, with a bootstrap dropdown menu

I'm having trouble triggering the dropdown in Bootstrap by clicking on a radio button. It seems like a simple task, but I've been struggling with it all day. According to Bootstrap documentation, you can activate the dropdown using a hyperlink o ...

Checking dynamically if a key-value pair exists in a JSON object

Here is some information that I have: "Vitals":[ { "Bp Systolic":"", "Bp Diastolic":"", "Weight":"", "Height":"", "BMI":"" } ], "Lab":[ { "Lipid_profile":[{ "Total Cholestrol":"", "TRIGLYCERID ...

Is there a modal confirmation feature available in Salesforce?

if ((Modal.confirm && Modal.confirm('some unique text')) || (!Modal.confirm && window.confirm('same but different text'))) navigateToUrl('another link here','ANOTHER DETAIL','submit'); I am curious about t ...

Identifying when a user has inputted incorrect $routeparams

How can I restrict user input to only "id" as a query parameter in the URL? $scope.$on('$routeUpdate', function () { var id = $routeParams.id //check if user has entered any params other than "id". //if yes do someting }); I want ...

What is the best way to access all of a class's properties in JavaScript?

Is there a way to retrieve all the properties of a class using JavaScript? For example, if I have a class like this: .menu { color: black; width: 10px; } How can I extract "color: black; width: 10px;" as a string using JavaScript? Thanks in advance! ...

Automatically move to the latest message as soon as it is posted

After trying multiple codes and encountering issues, I am attempting to add my message in a textarea that will automatically scroll down. Even though I have my own codes, they don't seem to work properly. I also tried using the code provided Here. ED ...

struggling with responseText functionality in javascript

I am encountering an issue with passing variables from PHP to JavaScript using JSON. The problem lies in the fact that I am able to debug and view the items in the responseText within my JavaScript, but I am unable to assign them to a variable or properly ...

Is there a way to adjust the colors of overlapping events in FullCalendar?

I'm currently working on a project involving Asp.Net MVC and I would like to incorporate Jquery fullcalendar into it. One feature I want is for a newly added event to change its color if there is already an existing event scheduled for the same day. ...