Executing a SQL function in a JavaScript file using ASP.NET C# - here's how!

I am currently working on a calendar project that retrieves entries from a SQL database. The calendar is being built programmatically in a JavaScript file, where I have hardcoded the code for generating the calendar cell for a specific day (in this case, it is represented by the variable counter). All I need to do is insert the query inside the function.

JavaScript File

  if (counter == 2 //2 is the Harcoded day
        && month == 8 //Hardcoded month
        && year == 2014) { //Harcoded year
            PageMethods.Msg(onSuccess);
            function onSuccess(response) {
                alert(response);
            }

            htmlContent += "<div class='user'>Data retrieved from DB goes here</div>";
            htmlContent += "<div class='client'>Data retrieved from DB goes here</div>";
            htmlContent += "<div class='num'>Data retrieved from DB goes here</div>";
            htmlContent += "<div class='status'></div>";
        }

I have created a method in the Code Behind, but I am unsure of how to pass the Object Div to get the query results and set them in the Divs. Or how to access the counter value in the query to retrieve results for specific days.

Code Behind

[System.Web.Services.WebMethod]
    public static string Msg()
    {
        return "Hello world";


        string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
        using (SqlConnection myConnection = new SqlConnection(connStr))
        {
            myConnection.Open();
            SqlCommand sqlCommand = new SqlCommand(" SELECT * FROM table",myConnection);


            //Add parameters to the query
            //<--- Where can I access the counter value from the JavaScript file? :( 


            SqlDataReader dr = sqlCommand.ExecuteReader();
            if (dr != null)
            {
                while (dr.Read())
                {
                    //<-- How do I set the query result to the divs here? :(

                }
            }
        }
    }

Answer №1

To enhance the loading speed of your calendar, it is recommended to utilize Ajax requests for data retrieval. However, if necessary, you can create an action that prepares the data and sends it as a parameter to the view. Instead of using <script> tags in the view, insert your code directly into the designated area.

Here is an example:

Action

public ActionResult MyJS()
{
    List<DateTime> calendar = new List<DateTime>();

    calendar.Add(DateTime.Parse("2010-03-21 12:00"));
    calendar.Add(DateTime.Parse("2011-03-21 12:00"));
    calendar.Add(DateTime.Parse("2012-03-21 12:00"));

    return View(calendar);
}

View

@model List<DateTime>
@{
    Layout = null; // important
}
@foreach (var item in Model)
{
    <text> 
        alert(" @item.ToString() ");
    </text>
}

Don't forget to add

<script src="home/myjs"></script>
to your layout.

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

AngularJS: Unable to preserve the data

I'm currently working on an issue with saving updated functions using angularJS. I've managed to edit the data and update it on the database side, but the changes aren't reflecting on the frontend side unless I logout and login again. I need ...

Spinning a rectangular grid with JavaScript

I am currently developing my own version of Tetris. My main focus at the moment is creating a function that can rotate a 2D variable array by 90 degrees (or -90). For instance, if we have an array like: "-T-", "TTT" The expected outpu ...

UpdatePanel paired with GridView or JQuery combined with DataTables

I have experience working with Java, JSP, jQuery, JSON data from the server side, and custom HTML code with datatables. Recently, I've been tasked with a project in C#, where I was introduced to GridView and AJAXControl Toolkit. After reading some po ...

Customize URL based on selected button

My question may be a bit unclear, but I want to generate dynamic URLs that redirect users to specific pages based on the link clicked. For example: Parent page with links (a, b, c, x, y) User clicks on 'b' User is taken to a Node Page that play ...

What is the best way to assess a scope object within an ng-Class directive?

Whenever I click a button, it moves to the next item in an array. Once it reaches the last item in the array, I want to assign the "endButton" class to the button tag. I plan to use the ng-class directive within the HTML code to evaluate the expression. T ...

The fade-in effect will initiate from the start once the mouse leaves the element (with a

Currently, I am in search of a solution for improving the navigation menu I am developing. By clicking on this JSFiddle link, you can view the code in action. The issue I am facing is that the fadeIn effect should only occur when hovering over the nav-ite ...

Discover the best way to retrieve attribute values using jQuery

I'm struggling to retrieve the value of the attribute "_last_val" from my input, but I'm having trouble getting it. Here is what I have attempted: demo // Here is the HTML code <form method="post" action="" id="feedback_form"> <inpu ...

What is the best way to link a ListBox item with an item in my personal list?

Within my WPF application, I am working with a ListBox that contains the names of various "Gesture" objects. I am looking for the most effective way in C# to connect a ListBox item with its corresponding Gesture instance. Specifically, I want to be able ...

Combine two scope arrays in AngularJS

Is there a way to merge two arrays of scope in AngularJS within my controller so that I can display them in a single table? The merging would be based on a common field present in both arrays, similar to an SQL join operation where data from both tables ...

Is initialization of static class members done prior to the invocation of the static constructor?

While browsing the MSDN Documentation, I came across an interesting contradiction. The documentation states that static members are initialized before they are accessed for the first time, and even before the static constructor (if present) is called. F ...

The problem of "undefined function appendTo" is causing issues

My jQuery code looks like this: $(function() { var productTextTemplate = $('#product-text-template').html(); var productTemplate = $('product-template').html(); var product = productTextTemplate.appendTo(productTemplate); a ...

Chrome displaying an extJs Button image

Could it be that Chrome is evolving into the new IE in terms of CSS issues? Here is the code I have for creating ExtJS buttons within an accordion: var button = Ext.create('Ext.Button', { text: '<img src="'+resp.sellers.externa ...

When executing the app.delete function, the req.body is found to be empty

I've encountered an issue when trying to send JSON data in an $http Delete call, as the req.body returned is coming back as an empty JavaScript object. Below is my $http delete call where "scenario" is a json object: //Deletes the item from the data ...

VueJS: Passing instance data to a method within an anonymous event handler situation - How to do it?

When testing the accessibility of Vue event binding to instance state/data, I encountered an issue. I attempted passing msg (instance data) into an anonymous function which then calls alertMsg(msg) (an instance method). However, it appears that only the de ...

Windows location does not change after an XMLHttpRequest is made

Here is my code that uses XMLHttpRequest: function SignUp() { signUpConnection = new XMLHttpRequest(); signUpConnection.onreadystatechange = processRegistration; signUpConnection.open('GET', 'index.php?registrarse=&username= ...

The functionality of $watch in AngularJS is not meeting the desired outcomes

Within my controller, I am looking to receive notifications when the value of a certain variable changes. Specifically, I want a function to be triggered whenever this variable is updated. To achieve this, I am utilizing the $watch method in AngularJS. Her ...

Using jQuery to upload files and send additional form data

When users upload a PDF file, I need to include additional data in the database. There are two radio buttons for selecting the type of document. How can I store the 'doctype' along with the uploaded file in the database? I have gone through the f ...

Using Fabric JS to update the image source of an element with a new URL

Can the src attribute of a fabric js object be changed to a CDN url? { version: '4.4.0', objects: [ { type: 'image', version: '4.4.0', originX: 'left', ... src:'www.cdn ...

Guide to writing Assert.IsTrue in Selenium using C#

Important Reminder for Holiday Deliveries To ensure timely delivery, please place your order before November 24th to avoid any Christmas postal delays I need some help with testing the text above on a specific page. Can someone review my code as I keep e ...

What are the best scenarios for implementing anonymous JavaScript functions?

I am currently exploring the reasons behind using anonymous JavaScript functions. Can you list out the distinctions between these functions? Describe scenarios where each function would be appropriate to use. var test1 = function(){ $("<div />" ...