My goal is to develop a .NET Web API without utilizing MVC in order to efficiently save and retrieve data from a SQL database

My goal is to develop a Web API in .NET without using MVC that can store and retrieve data from an SQL database. The aim is to then utilize this API in another web application by leveraging JavaScript. The data to be stored will include fields for Id, comment, date, and name.

While attempting to implement the functionality in the Repository class, I encountered issues with the following code:

public string insertJsonData(JsonInfo json)
{

    string message;
    SqlConnection connection = null;
    string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
    connection = new SqlConnection(connectionString);
    SqlCommand command = new SqlCommand("INSERT INTO JsonDataTable(JsonValue, CommentDate, ModelName) VALUES(@JsonValue, @CommentDate, @ModelName)", connection);
    
    connection.Open();
    
    command.Parameters.AddWithValue("@JsonValue", json.JsonData);
    command.Parameters.AddWithValue("@CommentDate", json.CommentDate);
    command.Parameters.AddWithValue("@ModelName", json.ModelName);
    
    int executionResult = command.ExecuteNonQuery();
    
    if (executionResult == 1)
    {
        message = json.JsonData + " details inserted successfully";
    }
    else
    {
        message = json.JsonData + " details not inserted successfully";
    }
    
    connection.Close();
    
    return message;
}

Answer №1

To send a string as JSON data back to the client, you can utilize the

JavaScriptSerializer class (make sure to include the reference to System.Web.Extensions)
and make the following substitution:

return Message;

with

return new JavaScriptSerializer().Serialize(Message);

When working with javaScript, you can then process and extract the response by doing:

const obj = JSON.parse(response);

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

What is the best way to load an ExtJS combobox with a JSON object that includes an array

After retrieving the following JSON from the backend: { "scripts": [ "actions/rss", "actions/db/initDb", "actions/utils/MyFile", "actions/utils/Valid" ], "success": true } The JSON data is stored as follows: t ...

Developing a Vue.js application with a universal variable

In the previous version of Vue.js, 0.12, passing a variable from the root component to its children was as simple as using inherit: true on any component that needed access to the parent's data. However, in Vue.js 1.0, the inherit: true feature was r ...

A bug in the modal dialog is causing it to disregard the value of

I want to transfer certain modal properties in this manner service.confirm = function(message, confirmProperties) { return $uibModal.open({ templateUrl: 'app/modal/alert/alert.tpl.html', controller: 'alertCon ...

Navigating to different HTML pages using JavaScript

Currently, I am working on transitioning from my login.html to account.html using JavaScript. In the login.html file, there will be a validation process using MongoDB. If the data matches, it should redirect to account.html; however, this is not happening ...

Using arrow functions in Typescript e6 allows for the utilization of Array.groupBy

I'm attempting to transform a method into a generic method for use with arrow functions in JavaScript, but I'm struggling to determine the correct way to do so. groupBy: <Map>(predicate: (item: T) => Map[]) => Map[]; Array.prototype ...

"Enhancing Interactivity: Leveraging Node.js and jQuery/Ajax for Liking and

I'm currently working on a project involving jQuery and Ajax, specifically with like/unlike buttons (marking/unmarking). The issue I'm facing is that the functionality of my buttons is not working as intended. Below is a snippet of my code, whic ...

Drawing images on a Canvas using specified coordinates: A step-by-step guide

https://i.stack.imgur.com/YkibI.jpg I've been trying to position images on specific coordinates, but I'm having trouble getting the shapes and angles right. Currently, only the top left corner is matching correctly. var _width, _height; var im ...

Tips for preventing the occurrence of a final empty line in Deno's TextLineStream

I executed this snippet of code: import { TextLineStream } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7201061632425c4341445c42">[email protected]</a>/streams/mod.ts"; const cm ...

Firefox throwing an error with jQuery URL Get requests

Could someone help me understand why my JavaScript function is triggering the error function instead of the success function in Firefox on Ubuntu? $(document).ready(function() { console.log( "Begin" ); $.ajax({ type: "GET", dataType: "ht ...

Remove numerous records from Azure Table Storage

About my current setup: In Azure, I am running a Node.js Web App that utilizes Azure Table Storage for data storage. To interact with the table storage, I rely on the azure-storage npm module. What I aim to achieve: The system I have set up is responsib ...

My attempt to adjust the word form based on the quantity is not functioning as expected

Having trouble making a noun plural based on a count and need some help understanding the issue. // PLEASE DO NOT MODIFY THE FOLLOWING INPUTS. const noun = prompt("Enter a noun"); const count = prompt("Enter a number"); console.log(nou ...

Upgrade button-group to dropdown on small screens using Bootstrap 4

I am currently developing a web application and incorporating Bootstrap 4 for certain components such as forms and tables. Within the design, I have included buttons grouped together to display various actions. Below is an example code snippet: <li ...

Ending the Overlay

I am using an overlay: <div id="overlayer" class="overlayer"> <div id="board" class="board"></div> </div> Here are the CSS properties I have applied to it: #overlayer { position:fixed; display:none; top:0; left:0; width:100%; hei ...

Is it possible to reach this result without relying on Modernizr?

Due to personal reasons that I won't delve into, my goal is to replicate the functionality of this menu : demo : http://tympanus.net/codrops/2013/04/19/responsive-multi-level-menu/ However, I want to achieve this without using Modernizr and poss ...

Authenticate users using JavaScript usernames

Below is my registration link that opens a modal: <a href="#registermodal" data-toggle="modal">Register Here</a> Here is the code for the modal dialog: <div class="modal fade" id="registermodal" role="dialog" style="overflow: scroll;"> ...

Attempting to create a multi-page slider using a combination of CSS and JavaScript

Looking for help with creating a slider effect that is triggered when navigating to page 2. Ideally, the div should expand with a width of 200% or similar. Any assistance would be greatly appreciated! http://jsfiddle.net/juxzg6fn/ <html> <head& ...

Implementing dynamic styling using ngClass and click event in AngularJS

Is there a way to toggle the class of a button when it's clicked and revert it back to its original state when clicked again? $scope.like_btn = "icon ion-ios-heart"; $scope.like_btn2 = "icon ion-ios-heart assertive"; $scope.likepic=function() { e ...

Is there a way to simplify my code and improve readability without sacrificing performance?

After completing the development of an explosive hoverboard model, it is now live on my website: . However, the code I've written seems to be quite messy and I'm struggling to optimize it without compromising performance. Is there a way to effici ...

Slick slider malfunctioning within bootstrap 4 framework

Despite following the instructions on the official slick slider website, I am encountering an issue where the slider is not working as expected. Instead of sliding through the images, they are being displayed on top of each other. Here is the code I have ...

When loading a page for the first time, the Vue.js transition does not take effect

After setting up a navbar that switches between two components, I encountered an issue with the fade-in animation not running when the page is first opened. The animation only works when using the navbar links to switch components. Any suggestions on how t ...