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>
  
<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>
  
<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);
}