Guidelines for displaying JSON data in HTML <ul><li></li></ul> format using jQuery within an ASP.NET environment

I am currently developing an asp.net application that involves fetching data from a database in JSON format and displaying it within html ul-li tags using jQuery. Below is a snippet of my Html Page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script language="javascript" type="text/javascript">
    //function GetCompanies() {
    $(document).ready(function () {

       $.ajax({
    type: "POST",
    url: "MobileServices.asmx/BindCategory",
    data: "{}",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    async: true,
    success: OnSuccess,
    error: OnError
});

function OnSuccess(data) {
    $.each(data, function (key, value{
        $("#ulCategory").append("<li><a rel=external href=Category_News.html?ID=" + value.Category_ID + ">" + value.Category_Name + "</li>");
    })

}
function OnError(data) {

}
    });
</script>
</head>
<body>
<form id="form1" runat="server">
    <div>
        <ul id="ulCategory">

        </ul>
    </div>
</form>
</body>
</html>

Here is the WebService code to access the data:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using Newtonsoft.Json;
using System.Configuration;
namespace MobileNewsAppication
{
/// <summary>
/// Summary description for MobileServices
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]


    [System.Web.Script.Services.ScriptService]
    public class MobileServices : System.Web.Services.WebService
    {

        public class NewsCategory
        {
            public long Category_ID { get; set; }
            public string Category_Name { get; set; }
            public string QFlag { get; set; }
        }



        [WebMethod]
        public string BindAllCategory()
        {
            DataTable dt = new DataTable();
            //List<NewsCategory> details = new List<NewsCategory>();

            using (SqlConnection con = new SqlConnection(Connection))
            {
                SqlCommand cmd = new SqlCommand("AllCategory_Select", con);
                cmd.CommandType = CommandType.StoredProcedure;

                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                return JsonConvert.SerializeObject(dt);

            }

        }
    }
    }

Unfortunately, I'm facing an issue where the ul tag does not bind any list items inside. I suspect that the foreach loop defined within the jQuery OnSuccess method may be incorrect. Any assistance would be greatly appreciated.

Answer №1

If it's not a mistake here, then the syntax error might be causing the success callback to fail...

function OnSuccess(data) {
//  $.each(data, function (key, value{ <- this is incorrect
    $.each(data, function() {
        $("#ulCategory").append("<li><a rel='external' href='Category_News.html?ID=" + this.Category_ID + "'>" + this.Category_Name + "</li>");
    });
}

Consider using this within each instead. I also added quotes around the link attributes. If that doesn't resolve the issue, add console.log(data); as the first line of the success callback and review the console for any errors.

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

Print the information obtained from a synchronous AJAX request in the console

I'm struggling to wrap my head around this issue. I am attempting to save the data from a synchronous ajax call in a variable and then log it to the console. However, the final console log is executing before the synchronous call has completed, so it ...

JavaScript's Extended Array feature is not functioning as anticipated, and no error message is being displayed

Hello, I am currently delving into JavaScript for a project I'm working on and have encountered a question regarding the following snippet of code. function randomArr(){}; randomArr.prototype = new Array(); randomArr.prototype.getRandomValue = funct ...

Is there a way to dynamically toggle the visibility of a floating textarea between on and off?

I have my own blog website: Essentially, what I am aiming for is When a user clicks on the search button, a floating semi-transparent textarea window should appear inside the designated rectangle area (as shown in the image, that red orange rectangle). ...

Encountering a TypeError indicating that the asterisk is not functioning as a proper function

Whenever I run my server.js file, an error keeps popping up: TypeError: routing is not a function This occurs in the following line of code: routing(app); In my routing.js file, the content looks like this: // JavaScript source code var friends = requ ...

Wrapping text in DataTables

I am experiencing an issue with the cell content below: <td style="max-width:200px;" class="sorting_1"> <i class="fa fa-circle text-success"></i> <span style="width: 200px;"> Публикация: "The Myth of Ponce de León an ...

Angular: Utilizing Nested ng-repeat Alongside groupBy Feature on Initial Page Load or Refresh

With some help, I've made it this far on my project. However, I need to take one more step to achieve my goal. I want to group data based on an attribute that is currently passed through an ng-click action. Is there a way to automatically do this on p ...

Contrast the values across various template sections

Due to specific requirements, I need to apply a bit of styling (margin) to the footer of the page. This styling should only be visible when the content section of the page is a product archive. I attempted to create a variable in the archive-products.php ...

Stop the Sidebar from showing up on certain pages with Next.js

Currently, I am facing a small issue with my application. The problem lies in the sidebar that appears on my login.jsx page when I specifically do not want it there. However, I would like it to appear on all other pages except for this one. Is there a cond ...

Can you guide me in utilizing this API endpoint efficiently to enable search functionality using React Query?

const { isLoading, isError, data, error, refetch } = useQuery( "college", async () => { const { result } = await axios( "http://colleges.hipolabs.com/search?name=middle" ); console.log(&quo ...

Resolving the "TypeError: $ is not a function" issue on a custom WordPress page

I developed a unique WordPress page using a custom plugin, where I aim to switch comments on and off with the following code: <script type="text/javascript> $("comment_switch").click(function () { $("comments").toggleClass("hidden"); }); < ...

What is the significance of utilizing app.set() and app.get() in applications?

Is there a way to simplify this code: app.set('port', (process.env.PORT || 3000)); const server = app.listen(app.get('port'), () => { console.log('Server|Port: ', app.get('port')); }); Here is an alternative ...

Modify the data within the JSON array using Github Actions

I currently have a JSON file with the following structure stored in the directory where my Github action is running - { "version":"1", "sampleArray":[ { "id":"1" } ], "secondArray":[ { "secondId":"2" } ...

What is the process by which nodejs interprets and analyzes c++ code?

My expertise lies in Javascript, but I'm intrigued by the connection between Node.js and C++. Despite their differences, I wonder how they interact and communicate with each other. ...

Issues arise when trying to use the Jquery append() method in conjunction with Angular

We are currently utilizing jquery version 1.9.1 and angular version 1.2.13 for our project. Our wysiwyg editor is functioning well, as we are able to save HTML into the database and load it back using the jquery append function successfully. However, we ar ...

Obtain span value using a CSS selector in Python

I need help extracting the value of a span using a CSS selector soup = BeautifulSoup("<body><main><div class='rentalprice'><span>3.000</span></div></main></body>") pagecontent = soup.find( ...

Is there a way to ensure that a table cell appears on a new line?

I am struggling with formatting an HTML table created by an MVC WebGrid. The table has 5 columns, and I want the first 4 columns to occupy 100% of the width while the 5th column sits underneath also taking up 100% of the width. <tr> <td cla ...

ASP.NET .aspx HTML code template for website development

My goal is to implement code templating in ASP.NET, harnessing the flexibility of PHP. Both snippets of code below produce the same outcome, however, the PHP version is deemed more elegant and can easily be imported into other PHP files for reusability. A ...

Having trouble mocking Node fs Modules using Sinon

I am facing an issue with mocking the promises methods of the node fs module in my code. When my appData.ts file is executed, it calls the actual fs.promises.mkdir method instead of the mock function defined in \__tests__/appData.test.js. I suspect ...

While everything ran smoothly on my local machine, the app crashed on Heroku as soon as I integrated express-handlebars into the

After adding this code to the app, it started crashing on Heroku servers. Interestingly, removing these codes resolved the issue and the app worked perfectly on Heroku. However, the app works fine with these codes when tested locally. const exphbs = req ...

JavaScript code for sorting a table based on a time interval

There is an index file with a flight schedule table. The table allows sorting by airline and departure time, as well as filtering by airline name. I'm trying to figure out how to add filtering by time range, specifically departing flights between 8 AM ...