Can we delete a list of Ids from database? - sql

Can we delete a list of Ids (int[]) in database from react? I have below and it doesn't work ... error message is: SyntaxError: Unexpected token 'M', "Microsoft."... is not valid JSON
==================================================
deleteIdList()
{
const idList = this.state.selectedEmployeeIdList;
if (window.confirm('Are you sure list of Employee(s)?'))
{
fetch(variables.API_URL + 'employee/' + idList, {
method : 'DELETE',
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}
})
.then(res=>res.json())
.then((result) => {
alert('deleted')
alert(result);
this.refreshList();
},(error)=>{
alert('Cannot Delete Selected Employee(s)!!!!! ' + error);
})
}
}
In VS 2019:
[HttpDelete("{id}")]
public JsonResult Delete(int[] id)
{
string query = #"DELETE FROM DBO.EMPLOYEE WHERE EMPLOYEEID in #EMPLOYEEIDs";
DataTable table = new DataTable();
SqlDataReader dr;
string sqlDataSource = _configuration.GetConnectionString("EmployeeAppConn");
using (SqlConnection myConn = new SqlConnection(sqlDataSource))
{
myConn.Open();
using (SqlCommand cm = new SqlCommand(query, myConn))
{
cm.Parameters.AddWithValue("#EMPLOYEEIDs", id);
dr = cm.ExecuteReader();
table.Load(dr);
dr.Close();
myConn.Close();
}
}
return new JsonResult("Employee #" + id.ToString() + " deleted!");
}

Related

ASP.NET CORE MVC With Google Charts - No Data

Trying to implement Google Chart with ASP.Net CORE MVC.
Been at it for two days, but I can not figure out my mistake. I don't get an error, and I can see the array in the console, but no data.
VIEWMODEL
public class ZipCodes
{
public string ZipCode { get; set; }
public int ZipCount { get; set; }
}
CONTROLLER
public ActionResult IncidentsByZipCode()
{
var incidentsByZipCode = (from o in _context.Incident
group o by o.ZipCode into g
orderby g.Count() descending
select new
{
ZipCode = g.Key,
ZipCount = g.Count()
}).ToList();
return Json(incidentsByZipCode);
}
VIEW
function IncidentsByZipCode() {
$.ajax({
type: 'GET',
url: '#Url.Action("IncidentsByZipCode", "Controller")',
success: function (response) {
console.log(response);
var data = new google.visualization.DataTable();
data.addColumn('string', 'ZipCode');
data.addColumn('number', 'ZipCount');
for (var i = 0; i < response.result.length; i++) {
data.addRow([response.result[i].ZipCode, response.result[i].ZipCount]);
}
var chart = new google.visualization.ColumnChart(document.getElementById('incidentsByZipCode'));
chart.draw(data,
{
title: "",
position: "top",
fontsize: "14px",
chartArea: { width: '100%' },
});
},
error: function () {
alert("Error loading data!");
}
});
}
Because the api you use is not Column Chart, the data cannot be added and rendered correctly. According to the official example, you need to make some changes.
Here is the ajax code.
<script>
//Generate random colors
function bg() {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + ',' + g + ',' + b + ")";
}
function IncidentsByZipCode() {
$.ajax({
type: 'GET',
url: '#Url.Action("IncidentsByZipCode","home")',
success: function (response) {
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
var obj = [
["Element", "Density", { role: "style" }],
];
$.each(response, function (index, value) {
obj.push([value.zipCode, value.zipCount, bg()])
})
var data = google.visualization.arrayToDataTable(obj);//This is method of Column Chart
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2]);
var chart = new google.visualization.ColumnChart(document.getElementById('incidentsByZipCode'));
chart.draw(data,
{
title: "",
position: "top",
fontsize: "14px",
chartArea: { width: '100%' },
});
}
},
error: function () {
alert("Error loading data!");
}
});
}
IncidentsByZipCode()
This is the controller.
public ActionResult IncidentsByZipCode()
{
//var incidentsByZipCode = (from o in _context.Incident
// group o by o.ZipCode into g
// orderby g.Count() descending
// select new
// {
// ZipCode = g.Key,
// ZipCount = g.Count()
// }).ToList();
var incidentsByZipCode = new List<ZipCodes>
{
new ZipCodes{ ZipCode="code1", ZipCount=3},
new ZipCodes{ZipCode="code2",ZipCount=4},
new ZipCodes{ZipCode="code3",ZipCount=2},
new ZipCodes{ZipCode="code4",ZipCount=9},
};
return Json(incidentsByZipCode);
}
Result, and you can also refer to this document
.

Class mapping using dart

I have this class(dart)
class ResumenPublicaciones {
String name;
String count;
ResumenPublicaciones({this.name, this.count});
// named constructor
ResumenPublicaciones.fromJson(Map<String, dynamic> json)
: name = json['name'],
count = json['count'].toString();
}
I want to map this response from the API
[{"name":"Administración","count":37},{"name":"Call Center,
Teletrabajo y Telemarketing","count":4},{"name":"Compras,
Importaciones, Logística, Distribución","count":10}]
this is how Im doing it....
class ServicioResumenEmpleos {
List<ResumenPublicaciones> publicaciones = [];
List getResumenPublicacioness() {
publicacionesResumidas();
return publicaciones;
}
var apiUrl = "here my api URLs";
Future<ResumenPublicaciones> publicacionesResumidas() async {
var jsonResponse;
Map<String, String> headers = {
'Content-Type': 'application/json',
};
var response = await http.get(apiUrl, headers: headers);
print('respuesta del api' + response.toString());
if (response.statusCode == 200) {
print(' el API responde ' + response.body);
jsonResponse = json.decode(response.body);
var _listapublicaciones = new ResumenPublicaciones.fromJson(jsonResponse);
publicaciones.add(_listapublicaciones);
print(_listapublicaciones.name);
return _listapublicaciones;
} else {
print(
'Esta imprimiendo el else en este punto no debe impremir el response');
var _listapublicacionesNull = new ResumenPublicaciones();
_listapublicacionesNull.count = '0';
_listapublicacionesNull.name = 'didnt work';
return _listapublicacionesNull;
}
}
//
}
I want to receive a list on the class but im receiving this error msg
Exception has occurred.
**_TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>')**
any Idea of what im doing wrong?
The problem is here:
var _listapublicaciones = new ResumenPublicaciones.fromJson(jsonResponse);
If your response is a list, you are passing it to a constructor that is expecting a Map. You need to iterate over the objects of your list and convert them into individual publicaciones:
var _listapublicaciones = (jsonResponse as List).map(
(o) => ResumenPublicaciones.fromJson(o),
).toList();

Management dates on sql server with node.js

the code below performs a select on a sql server database, when the code is executed the following error is generated, i have this error: TypeError: parameter.value.getTime is not a function
Input Parameter:
IdUtente=2
dataInizio=01-07-2018
datafine=02-09-2018
Date:
01-08-2018
01-10-2018
01-11-2018
02-01-2019
02-08-2018
JavaScript:
async function CaricaDataeTotaleOre(IdUtente,dataInizio,datafine) {
console.log("Carica Data e Totale Ore -- IdUtente: "+IdUtente+"\n Data Inizio: "+dataInizio+"\n Data Fine: "+datafine);
var data = [];
var query = "SET LANGUAGE 'Italian' SELECT Distinct CONVERT(varchar(10), DataCreazione, 105) as Data FROM Marcatura inner join Utente on Utente.IdUtente = Marcatura.IdUtente where Utente.IdUtente = #IdUtente and(CONVERT(VARCHAR(10),Marcatura.DataCreazione,103) between #Start and #End) ";
const ret = await new Promise((resolve, reject) => {
new sql.ConnectionPool(DbConfig.config).connect().then(pool => {
return pool.request().input('IdUtente', sql.Int, IdUtente).input('Start', sql.DateTime, dataInizio).input('End', sql.DateTime, datafine).query(query)
}).then(result => {
resolve(result);
sql.close();
}).catch(err => {
ManageError.SendError("Errore CaricaDataeTotaleOre con : " + IdUtente + "\n Errore: " + err);
reject(err)
sql.close();
});
});
for (var i = 0; i < ret.recordset.length; i++) {
data.push({
Data: ret.recordset[i].Data
})
}
return data;
}

Is 'var' a reserved word in VB.NET?

While running the following code below, I received the following error:
Type 'var' is not defined.
Is 'var' a reserved word in VB.NET?
If not, why am I getting this error and how do I resolve it?
<WebMethod()> _
Public Shared Function SaveData(empdata As String) As String
Dim serializeData = JsonConvert.DeserializeObject(Of List(Of Employee))(empdata)
Using con = New SqlConnection(Constr)
For Each data As var In serializeData
Using cmd = New SqlCommand("INSERT INTO Employees VALUES(#Fname, #Lname,#Email,#CreatedDate)")
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#Fname", data.FName)
cmd.Parameters.AddWithValue("#Lname", data.LName)
cmd.Parameters.AddWithValue("#Email", data.EmailId)
cmd.Parameters.AddWithValue("#CreatedDate", DateTime.Now)
cmd.Connection = con
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.ExecuteNonQuery()
con.Close()
End Using
Next
End Using
Return Nothing
End Function
'Updated:
function getAllEmpData() {
var data = [];
$('tr.data-contact-person').each(function () {
var firstName = $(this).find('.spousename01').val();
var lastName = $(this).find('.spouseaddress01').val();
var emailId = $(this).find('.spouseincome01').val();
var alldata = {
'FName': firstName,
'LName': lastName,
'EmailId': emailId
}
data.push(alldata);
});
console.log(data);
return data;
}
$("#btnSubmit").click(function () {
var data = JSON.stringify(getAllEmpData());
//console.log(data);
$.ajax({
url: 'closures.aspx/SaveData',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'empdata': data }),
success: function () {
alert("Data Added Successfully");
},
error: function () {
alert("Error while inserting data");
}
});
});

Get dropdown value and text in controller mvc4 razor

I am working on MVC4 project. I have form where dropdownlist is populated with text and value field.
#Html.DropDownList("SourceDropDownList", new SelectList(""), "-Select-", new { #class = "validate[required]" })
This dropdown is populated from other dropdown change event
here is that code
function OnSourceFacilityDropDownChange(source, e) {
$("#SourceDropDownList").empty();
var curOpt = new Option('-Select-', "");
$("#SourceDropDownList").get(0).options[$("#SourceDropDownList").get(0).options.length] = curOpt;
if (source.value != '') {
var url = getUrl() + '/AdminPanel/GetIns/?id=' + Math.random();
$.ajax({
url: url,
data: { clientid: $("#SourceDropDown").val(), strFacility: source.value }, //parameters go here in object literal form
type: 'GET',
datatype: 'json',
success: function (data) {
$.each(data, function (index, item) {
var curOpt = new Option(item.T, item.T);
curOpt.setAttribute("title", item.T);
$("#SourceDropDownList").get(0).options[$("#SourceDropDownList").get(0).options.length] = curOpt;
});
},
error: function (request, status, error) { alert("Status: " + status + "\n Exception Handling : \n" + request.responseText); },
complete: function () {
$("#divLoading").hide();
}
});
}
else {
}
}
and code in AdminPanel/GetIns controller is
public JsonResult GetInspection(int clientid, string strFacility)
{
var objlist = (from d in Context.tbl_insp
orderby d.str_insp ascending
where d.clientid.Equals(ClientId))
select new { T= d.str_inspname, V= d.dte_start.Value.ToShortDateString()}).ToArray();
Array InspectionList = objlist;
return Json(InspectionList, JsonRequestBehavior.AllowGet);
}
And in model class i have initialized the property of dropdown
public string SourceDropDownList{ get; set; }
now i am getting only text values of what i select in SourceDropDownList dropdown..
How do i get the value also ??
Try with this,Just Example
View
#Html.DropDownList("CustomerId", (SelectList)ViewBag.CustomerNameID, "--Select--")
#Html.DropDownList("CustomerNameId", new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "-- Select --")
Script
<script type="text/javascript">
$(document).ready(function () {
$("#CustomerId").change(function () {
var Id = $("#CustomerId").val();
$.ajax({
url: '#Url.Action("GetCustomerNameWithId", "Test")',
type: "Post",
data: { CustomerNameId: Id },
success: function (listItems) {
var STSelectBox = jQuery('#CustomerNameId');
STSelectBox.empty();
if (listItems.length > 0) {
for (var i = 0; i < listItems.length; i++) {
if (i == 0) {
STSelectBox.append('<option value="' + i + '">--Select--</option>');
}
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
else {
for (var i = 0; i < listItems.length; i++) {
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
}
});
});
});
</script>
Controller
public JsonResult GetCustomerNameWithId(string CustomerNameId)
{
int _CustomerNameId = 0;
int.TryParse(CustomerNameId, out _CustomerNameId);
var listItems = GetCustomerNameId(_CustomerNameId).Select(s => new SelectListItem { Value = s.CID.ToString(), Text = s.CustomerName }).ToList<SelectListItem>();
return Json(listItems, JsonRequestBehavior.AllowGet);
}
Model
public class CustomerModel
{
public int CustomerId { get; set; }
public int CustomerNameId { get; set; }
}