Is 'var' a reserved word in VB.NET? - 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");
}
});
});

Related

Can we delete a list of Ids from database?

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

How to pass pdf file to Controller that requires IFormFile

I've been working on this the whole day and did my research already, I can't seem to find a solution anywhere. I have this function that calls a List in my controller, the List needs a IFormFile parameter,
here's my javascript method
function fileUploader_uploaded(e) {
const file = e.file;
const fileReader = new FileReader();
fileReader.onload = function () {
toggleDropZoneActive($("#dropzone-external")[0], false);
$("#dropzone-item")[0].data = fileReader.result;
}
fileReader.readAsDataURL(file);
const _fileReader = new FileReader();
var r = _fileReader.readAsBinaryString(file);
$("#dropzone-text")[0].style.display = "none";
$.ajax({
url: '#Url.Action("_Index", "FileUploader")',
data: { CFile: r}, // I'm trying to pass the pdf file here
cache: false,
success: function (data) {
console.log(data);
}
});
}
and this is my List in controller
public object _Index(IFormFile CFile)
{
if (CFile != null)
{
try
{
string documentText = "";
using PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor();
documentProcessor.LoadDocument(CFile.OpenReadStream());
documentText = documentProcessor.Text;
string word = #"([0-9]+.[0-9]+-[0-9]+)";
Regex regex = new Regex(word);
foreach (Match match in regex.Matches(documentText))
{
sectionsList.Add(match.Value.ToString());
}
}
catch
{
Response.StatusCode = 400;
}
}
else
{
_logger.LogInformation("empty");
}
return sectionsList;
}
the CFile is always empty i tried different ways already like passing
data: { CFile: e.file}
Does anyone else have idea?
From this code data: { CFile: e.file}, you post it as the string, so it can not be recognized as a file. You need to use FormData and change the contentType.
function fileUploader_uploaded(e) {
const file = e.file;
const fileReader = new FileReader();
fileReader.onload = function () {
toggleDropZoneActive($("#dropzone-external")[0], false);
$("#dropzone-item")[0].data = fileReader.result;
}
fileReader.readAsDataURL(file);
const _fileReader = new FileReader();
var r = _fileReader.readAsBinaryString(file);
$("#dropzone-text")[0].style.display = "none";
//----------edit here---------
var form = new FormData()
form.append('CFile', file)
$.ajax({
url: '#Url.Action("_Index", "FileUploader")',
method:'post',
data: form,
cache: false,
contentType: false,
processData: false,
success: function (data) {
}
});
}
The bakend should add [FromForm].
[HttpPost]
public object _Index([FromForm]IFormFile CFile)

How to pass HTML(View) Table data to controller to save in slq table

I am calculating the some values based on data available for previous month and displaying in table format in view. I have another model where I need to pass these values and save in database. I am not inputting any value, either values are static or calculated. Values are not passed from view to controller.
I have tried the jquery/ajax but not successful.
//Controller//
[HttpPost]
public JsonResult Proccess(List<ServerCount> deviceCounts)
{
if(deviceCounts == null)
{
deviceCounts = new List<ServerCount>();
}
var startOfTthisMonth = new DateTime(DateTime.Today.Year,
DateTime.Today.Month, 1);
var FromDate = startOfTthisMonth.AddMonths(-1);
var ToDate = startOfTthisMonth.AddDays(-1);
var billMonth = startOfTthisMonth.AddMonths(-1).ToString("MMM") + "-" + startOfTthisMonth.AddMonths(-1).ToString("yyyy");
ServerCount model = new ServerCount();
foreach (ServerCount sc in deviceCounts)
{
model.BillingMonth = billMonth;
model.ServiceName = sc.ServiceName;
model.BaslineVol = sc.BaslineVol;
model.ResourceUnit = sc.ResourceUnit;
model.DeviceCount = sc.DeviceCount;
model.DeployedServer = sc.DeployedServer;
model.RetiredServer = sc.RetiredServer;
_context.ServerCount.Add(model);
}
int insertRecords = _context.SaveChanges();
return Json(insertRecords);
}
==================
Jquery
<script type="text/javascript">
$(document).ready(function () {
$("body").on("click", "#btnSave", function () {
var deviceCounts = new Array();
$("#tblServerCount TBODY TR").each(function () {
var row = $(this);
var deviceCount = {};
deviceCount.ServiceName = row.find("TD").eq(0).html();
deviceCount.BaslineVol = row.find("TD").eq(1).html();
deviceCount.ResourceUnit = row.find("TD").eq(2).html();
deviceCount.DeviceCount = row.find("TD").eq(3).html();
deviceCount.DeployedServer = row.find("TD").eq(4).html();
deviceCount.RetiredServer = row.find("TD").eq(5).html();
deviceCounts.push(deviceCount);
});
var model = $("#MyForm").serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Proccess", "DeviceCountServers", new { Area = "Admin" })?' +model,
data: JSON.stringify(deviceCounts),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
location.reload();
});
});
});
</script>
I looking that data from table is saved to sql on click of button

Jqgrid: Access Selected Row Cell value in Code behind

I want to access the selected row cell id in the code behind. I can do it either by Ajax call but it is not possible when i try to send the data from the Jqgrid Subgrid.
Below is the Subgrid code:
subGridRowExpanded: function (subgrid_id, row_id) {
debugger;
var subgrid_table_id, pager_id; subgrid_table_id = subgrid_id + "_t";
var selected_row_id = $('#tblFormData').jqGrid('getCell', row_id, 'Category_Id')
// pager_id = "p_" + subgrid_table_id;
$("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table><div id='" + pager_id + "' class='scroll'></div>");
$("#" + subgrid_table_id).jqGrid({
// $("#tblTest").jqGrid({
url: "/Forms.aspx/GetFormsData", //?selected_row_id=" + selected_row_id,
data: '{"CategoryDesc":"' + selected_row_id + '"}',
datatype: "json",
contentType: "application/json; charset=utf-8",
loadonce: true,
width: "300",
height: "auto",
pager:"#tblSubpager",
colNames: ['FormName','FormPath'],
colModel: [
{ name: "FormName", index: "FormName", editable: true, formatter: 'showlink' },
//{ name: "FormPath", index: "FormPath", editable: true, hidden: true },
{
name: 'FormPath',
index: 'FormPath',
hidden: true,
enctype: "multipart/form-data",
editable: true,
edittype: 'file',
editrules: {
edithidden: true,
required: true
},
formoptions: {
elmsuffix: '*'
}
}
],
gridview: true,
autoencode: true,
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: {
root: function (obj) { return obj.d; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.d.length; }
}
});
below is the function which i call it from the URL in Vb.NET.
<WebMethod> _
<ScriptMethod(UseHttpGet:=True, ResponseFormat:=ResponseFormat.Json)> _
Public Shared Function GetFormsData(CategoryId As String) As List(Of Dictionary(Of String, String))
Using dt As DataTable = DirectCast(DataAccess.ExecuteStoredProcedure("AFI_DYNAMIC", "Ashley.dbo.usp_GetDownloadFormsDetails", DataAccess.StoredProcedureReturnType.DataTable), DataTable)
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim rows1 As New List(Of Dictionary(Of String, String))()
Dim rows As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object)
Dim row1 As Dictionary(Of String, String)
For Each dr As DataRow In dt.Rows
row = New Dictionary(Of String, Object)()
row1 = New Dictionary(Of String, String)()
For Each col As DataColumn In dt.Columns
row.Add(col.ColumnName, dr(col))
'string sb = "Yahoo!";
Next
rows.Add(row)
'For i As Integer = 0 To dt.Columns.Count - 1
Dim sb As String = "" & dr("FormName").ToString() & ""
'Next
row1.Add(dt.Columns(0).Caption, sb)
rows1.Add(row1)
Next
Return rows1
End Using
End Function
Now i want to Access the CategoryId in my code behind Can anybody help me on this.
The code have clear many problems. I post below some clear problems which I could find by reading of the code:
Is CategoryId the column of the parent grid? Is $('#tblFormData') the parent grid? In the case you could use $(this) instead of $('#tblFormData').
You use pager_id as id of <div> of the pager for subgrid, but the line which assign the value for pager_id is commented and id is undefined. Instead of that you use pager:"#tblSubpager" which is wrong.
jqGrid has no contentType parameter. So you should remove it. Instead of that you use already ajaxGridOptions parameter with contentType. It's correct parameter.
You use data: '{"CategoryDesc":"' + selected_row_id + '"}', but the server code expect parameter with the name CategoryId and not CategoryDesc. By the way jqGrid has no data parameter in case of usage datatype: "json". What you mean should be postData. Correct will be to use
postData: {
CategoryId: selected_row_id
}

jsonp syntax error unexpected token

if I use dataType: json I don't get an error in the response/
If I use dataType: jsonp I get the following error:
syntax error unexpected token
This is my jquery code
function testJsonp()
{
$.ajax({
type: "POST",
url: "http://localhost/FT8Services/FTService.asmx/testjsonp",
data: "{firstname: '" + encodeURIComponent("Stack") + "', lastname: '" + encodeURIComponent("Overflow") + "'}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (result) {
var loginfo = eval(result.d);
alert(loginfo[0]);
if(loginfo.length > 1)
{
alert("Sucess");
}
else
{
alert("no access");
}
},
error: function(xhr, status, error) {
alert(error);
}
})
}
and this is my asp.net web method
<WebMethod()> _
Public Function testjsonp(ByVal firstname As String, ByVal lastname As String) As String
Dim rdatas As New List(Of String)
Dim fullname As String = firstname & lastname
For i As Integer = 1 To 5
rdatas.Add(fullname & " " & i.ToString)
Next
Dim js As New JavaScriptSerializer
Dim strJSON As String = js.Serialize(rdatas.ToArray)
Return strJSON
End Function