What is Code to Pass JSON to a Stored Procedure
The SQL Server stored procedure should accept the JSON string as an NVARCHAR(MAX) parameter. You can use SQL Server's OPENJSON function to
parse the JSON and insert/update data as needed.
To convert the TravelClassModel data into a JSON
string, you would use JsonConvert.SerializeObject() method from the
Newtonsoft.Json library. Here's how you can serialize the TravelClassModel object into a JSON string, assuming you want to deserialize a list of TravelClassModel objects from a response:
using System.Data;
{
private readonly ILogger < HomeController > _logger;
_logger = logger;
}
return View();
return View();
// Step 1: Serialize the model to JSON string
var settings = new JsonSerializerSettings
DateFormatString = "yyyy-MM-dd HH:mm:ss.fff"
};
var jsonObj = JsonConvert.SerializeObject(salesInvoiceSetModel, settings);
var sqlparameters = new Dictionary < string, object>
{ "@strJSON", jsonObj }
var result = ExecuteStoredProcedureAsync("SP_Demo_Save", sqlparameters);
return View();
private async Task < DataTable > ExecuteStoredProcedureAsync(string procedureName, Dictionary < string, object > parameters)
DataTable resultTable = new DataTable();
using(SqlCommand command = new SqlCommand(procedureName, connection))
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue(param.Key, param.Value);
}
resultTable.Load(reader);
}
}
}
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
using Microsoft.AspNetCore.Hosting.Server;
public class ErrorViewModel
{
public string? RequestId { get; set; }
public class SalesInvoiceSetModel
{
public string InvoiceNumber { get; set; }
{
public string CustomerName { get; set; }
{
public string ItemCode { get; set; }
}
{
"Logging": {
}
},
"AllowedHosts": "*",
}
}
CREATE PROCEDURE SP_Demo_Save
AS
BEGIN
--Parse the JSON string and insert into the SalesInvoice table
INSERT INTO SalesInvoice(InvoiceNumber, InvoiceDate, CustomerName, TotalAmount)
SELECT
JSON_VALUE(@strJSON, '$.InvoiceNumber'),
JSON_VALUE(@strJSON, '$.InvoiceDate'),
JSON_VALUE(@strJSON, '$.CustomerDetails.CustomerName'),
JSON_VALUE(@strJSON, '$.TotalAmount');
--Parse and insert the items into the SalesInvoiceItems table
INSERT INTO SalesInvoiceItems(InvoiceNumber, ItemCode, ItemName, Quantity, UnitPrice)
SELECT
JSON_VALUE(@strJSON, '$.InvoiceNumber'),
Items.ItemCode,
Items.ItemName,
Items.Quantity,
Items.UnitPrice
WITH(
ItemCode NVARCHAR(50),
ItemName NVARCHAR(100),
Quantity INT,
UnitPrice DECIMAL(10, 2)
);
--Return a success message
SELECT 'Success' AS Status;
END
CREATE PROCEDURE SP_Demo_Save
AS
BEGIN
-- Process the JSON data (for example, use OPENJSON to parse and insert)
SELECT @strJSON -- Example: Returning the JSON for validation (you would parse and process it here)
END
CREATE PROCEDURE SP_Demo_Save
AS
BEGIN
-- Process the JSON data (for example, use OPENJSON to parse and insert)
SELECT @strJSON -- Example: Returning the JSON for validation (you would parse and process it here)
DROP TABLE IF EXISTS #SalesInvoice;
SELECT *
INTO #SalesInvoice
WITH
(
PKId UNIQUEIDENTIFIER '$.PKId',
NAME nvarchar(max) '$.PKId',
IsDeleted BIT '$.IsDeleted'
);
SELECT * FROM #SalesInvoice
END