How to insert data to table on SQL server using jQuery on blazor server side?

Ahmed Salah Abed Elaziz 390 Reputation points
2023-03-26T01:53:41.0833333+00:00

I work on blazor server side .I face issue I can't apply jQuery to insert data to SQL server database table owner .

after apply script and check table SQL server no rows inserted

so my issue jQuery not insert data

my code as below :

1 - I create JS file insertdata.js on wwwroot folder js folder and add following code :

function insertData(owner) {
                $.ajax({
                    type: 'POST',
                    url: '/api/Owner/AddOwnerFile',
                    data: JSON.stringify(owner),
                    contentType: 'application/json',
                    success: function () {
                        alert('Data inserted successfully!');
                    },
                    error: function () {
                        alert('Error inserting data!');
                    }
                });
            }

2 - web API will executed by jQuery as below

[HttpPost]
        public ActionResult AddOwnerFile(object owner)
        {
            var ownerDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(owner.ToString());
           
               string ownerfileno = ownerDict["employeeID"].ToString();
            
            
           
              string departementCode = ownerDict["departementCode"].ToString();
            
            
           

            var sql = "INSERT INTO Owner (OwnerFileNo, DepartementCode) VALUES ({0}, {1})";
            var rowsAffected = _context.Database.ExecuteSqlRaw(sql, ownerfileno, departementCode);

            return Ok();
         
        }

3 - on razor page I invoke function as below :

public async Task InsertData(EmployeeDetails owner)
    {
        await JS.InvokeAsync<object>("insertData", owner);
    }

4 - on _Host file my scripts file as below :

<head>
   
<script src="~/js/jquery-3.6.3.js"></script>

</head>
<body>
  
 <component type="typeof(App)" render-mode="ServerPrerendered" />

 <script src="~/assets/js/insertdata.js"></script>
 <script src="_framework/blazor.server.js"></script>


</body>
</html>

5-on html and related function insert as below :

  <span class="text-sm mb-0 text-capitalize font-weight-bold">Owner File No</span>
                                            &nbsp&nbsp
                                            <div class="autocomplete w-25">
                                                <input id="autocomp" @bind=selectedEmployeeId @oninput=HandleInput class="form-control filter" style=" width:200px;" />
                                                @if (emp is not null)
                                                {
                                                    <ul class="options">
                                                        @if (emp.Any())
                                                        {
                                                            @foreach (var em in emp)
                                                            {
                                                                <li class="option" @onclick=@(_ => Selectemp(em.employeeID))>
                                                                    <span class="option-text">@em.employeeID</span>
                                                                </li>
                                                            }
                                                        }
                                                        else
                                                        {
                                                            <li class="disabled option">No results</li>
                                                        }
                                                    </ul>
                                                }
                                            </div>
                                        </div>
                                    </div>
                                 
                                   
                                  
                                   
                                       
                                            <span class="text-sm mb-0 text-capitalize font-weight-bold" style="width:160px;">Department Code</span>
                                            &nbsp&nbsp
                                            <input type="text" class="form-control" @bind="@emddata.departementCode" />
                                    
                                
                                   
                                </div>
                         

@code
{
 public class EmployeeDetails
    {
        public int employeeID { get; set; }
        public string departementCode { get; set; }

    }
public EmployeeDetails emddata = new EmployeeDetails();
async Task  Selectemp(string id)
    {
        selectedEmployeeId = id;
        selectedEmployeeId = emp!.First(c => c.employeeID.Equals(selectedEmployeeId)).employeeID;
        appsdata.OwnerFileNo = selectedEmployeeId;
        InsertData(emddata);
          
}
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,780 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,664 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,301 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Chrish Palmons 0 Reputation points
    2023-07-28T17:48:39.0866667+00:00

    Hey Ahmed,

    Based on the provided code, I can see a few potential issues that might be causing the data not to be inserted into the SQL Server database.

    Database Context (_context): Ensure that the _context variable in your Web API (AddOwnerFile) is properly initialized and configured to connect to the correct database. Check that the _context is not null and that it's properly configured to perform the database operation.

    JSON Serialization: In the Web API AddOwnerFile method, you are deserializing the owner object using JsonConvert.DeserializeObject, but you are not specifying the correct type for deserialization. Instead of using Dictionary<string, object>, create a class representing the data structure for the owner object:

    //csharp

    public class OwnerData { public string EmployeeID { get; set; } public string DepartementCode { get; set; } } Then, use this class for deserialization:

    //csharp

    [HttpPost] public ActionResult AddOwnerFile([FromBody] OwnerData owner) { // Access owner.EmployeeID and owner.DepartementCode // ... rest of the code } JSON Property Names: Ensure that the property names in the OwnerData class match the property names being sent from the client-side JavaScript. For example, in the OwnerData class, the property name is EmployeeID, but in the JavaScript, you are using employeeID.

    Passing Data from JavaScript: In the JavaScript function insertData, make sure that the owner object passed to the AJAX request has the correct structure, corresponding to the OwnerData class:

    //javascript

    function insertData(owner) { $.ajax({ type: 'POST', url: '/api/Owner/AddOwnerFile', data: JSON.stringify({ employeeID: owner.employeeID, departementCode: owner.departementCode }), contentType: 'application/json', success: function () { alert('Data inserted successfully!'); }, error: function () { alert('Error inserting data!'); } }); } Database Permissions: Ensure that the user accessing the SQL Server database has the necessary permissions to perform the insert operation on the Owner table. Please make sure to address these points and see if it resolves the issue. Additionally, it's a good idea to check the browser console and server-side logs for any error messages that might provide further insight into the problem. If the issue persists, you can use console.log or debugging techniques to inspect the data being passed between the client and server-side to identify any discrepancies. I have implemented a bit of the same logic in one of client's site which is Keralajackpot.in

    0 comments No comments

  2. Bruce (SqlWork.com) 71,506 Reputation points
    2023-07-30T02:33:32.79+00:00

    your design makes no sense.

    blazor server is a server technology. currently the browser is sending an event to the server over signal/r, the you server code is send in a message to the browser, then the browser is making an ajax call back to the server.

    your webapi code is invalid, see above. the serializarion is invalid, and not actually should not be there anyway. the parameter should be the correct type.

    you should not use jquery with blazor projects (WASM or Server).

    the razor page event should just update the database.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.