Home > Back-end >  Passing values from JavaScript to C# ASP.NET Core Razor Pages for SQL Querying
Passing values from JavaScript to C# ASP.NET Core Razor Pages for SQL Querying

Time:12-04

I am making a simple web-shop application prototype and need to pass shopping cart items (which are stored in localStorage) to our SQLServer. The localStorage is as follows

{"grootfigure":{"name":"Groot figure","tag":"grootfigure","price":600,"inCart":2},"owlfigure":{"name":"Owl figure","tag":"owlfigure","price":350,"inCart":4},"dragonfigure":{"name":"Dragon figure","tag":"dragonfigure","price":475,"inCart":5}}

The first idea was to pass the quantity of each product in cart to each counter variable in C# and then use a separate method in C# to run an SQL Query. But this seemed difficult to accomplish.

When I tried to pass variables between JS and C# by

function addOwl(){
            @Globals.String = localStorage.getItem('productsInCart')
            alert(@Globals.String)

            
        }

I get this in the web browser console

Uncaught ReferenceError: addOwl is not defined at HTMLButtonElement.onclick (cart:71:68)

Any ideas how I can easily run SQL query from localStorage values? Thank you

CodePudding user response:

It's not a good idea to pass values from your JavaScript code directly to C# and run an SQL query with it, as this can leave your application vulnerable to SQL injection attacks. Instead, you should consider using an AJAX call to send the data from your JavaScript code to a server-side endpoint, where you can validate and sanitize the data before using it in an SQL query.

Here's an example of how you might do this:

  1. In your JavaScript code, create a function that gets the shopping cart data from localStorage and sends it to a server-side endpoint using an AJAX call:

function sendCartData() {
  // Get the shopping cart data from localStorage
  var cartData = localStorage.getItem('productsInCart');

  // Use jQuery's $.ajax() method to send the data to a server-side endpoint
  $.ajax({
    url: '/your-server-endpoint',
    type: 'POST',
    data: { cartData: cartData },
    success: function(response) {
      // Handle the response from the server
    }
  });
}

  1. On the server-side, create an endpoint that can handle the AJAX call and save the shopping cart data to your database. For example, if you're using ASP.NET Core, you might create an action method like this:

[HttpPost]
public IActionResult SaveCartData(string cartData) {
  // Validate and sanitize the cart data before using it in an SQL query

  // Use Entity Framework or another ORM to save the data to your database
  using (var db = new YourDbContext()) {
    // Create a new ShoppingCart object and populate it with the cart data
    var cart = new ShoppingCart {
      // Parse the cart data and populate the ShoppingCart object
    };

    // Save the ShoppingCart object to the database
    db.ShoppingCarts.Add(cart);
    db.SaveChanges();
  }

  // Return a success response to the client
  return Json(new { success = true });
}

This approach allows you to safely save the shopping cart data to your database, without exposing your application to SQL injection attacks. You may need to adjust the code to fit the specific needs of your application, but this should give you a good starting point.

CodePudding user response:

You need to understand where, when and how both JavaScript and C# are executed in Razor Pages.

C# is executed on the server, before the output is sent to the browser. Once the server executes the C# code, it produces text (which may be plain text, HTML, CSS, JavaScript, etc), which it then sends out. It then discards the request.

By contrast, JavaScript is only executed in the browser, not on the server. It knows nothng about C#, and cannot call C# code directly.

Specifically, the line of code...

@Globals.String = localStorage.getItem('productsInCart')

..will be interpreted by the server-side C# as "get the value of the String property of a C# object named Globals and insert that into the output that will be sent to the browser."

Given that you probably don't have that, I would expect a compiler error at this point. If you're not getting that, then it sounds like you aren't giving us the full story.

Assuming it can find such an object with such a property, let's say it has the value jim, it will mean that the following text (that's very important, the server treats all of this as text, it doesn't know about JavaScript, and will not attempt to interpret it) will be sent to the browser...

function addOwl(){
            jim = localStorage.getItem('productsInCart')
            alert(jim)

            
        }

This is almost certaily not what you want.

So, to answer your basic question, the way to send data from your JavaScript to the server, where it will be used in your C# is to use AJAX. There are other ways, but this is probably the simplest.

If you use jQuery, then it gives you JavaScript functions to make this relatively easy. You'll need to write some C# code to accept the AJAX request.

  • Related