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");
}
});
});
I have an handsontable and i am trying to read the array data in ASP.Net. i have the below code. When i send the data to server. i keep getting ParseError. I tried different ways but did not help.
var data = [
["Year", "Kia", "Nissan", "Toyota", "Honda"],
["2008", 10, 11, 12, 13],
["2009", 20, 11, 14, 13],
["2010", 30, 15, 12, 13]
];
var $container = $("#example1");
$container.handsontable({
data: data
});
function sendData() {
var $container = $("#example1");
var handsontable = $container.data('handsontable');
var myData = handsontable.getData();
$.ajax({
type: "POST",
url: "Test.aspx/SaveUser",
data: "{'data':" + JSON.stringify(myData) + "}",
dataType: "json",
success: function (response) {
alert("Data sent to server.");
window.location.reload();
},
error: function (xhr, status) {
alert("An error occurred: " + status);
}
});
}
Server side code
<WebMethod()> <ScriptMethod()> _
Public Shared Sub SaveUser(data As List(Of String))
Dim lstItems As List(Of Object) = New JavaScriptSerializer().ConvertToType(Of List(Of Object))(data)
End Sub
Please help me in reading the data and thanks in advance
I figured it out. Hope it helps others
just changed the line
data: '{data: ' + JSON.stringify(myData) + '}',
I'm a beginner in MVC. I have a column which must be shown as a picture (now it is a text) and also when user click to picture it shows the dialog with new view. As i googled, i can use formatter only one time, what should i use then to implement it?
{ name: 'SimType', label: 'SimType', template: columntemplates.textTemplate, width: 50, editable: true, editrules: { edithidden: false }, formatter: linkFormat2, unformat: linkUnFormat2, editoptions: { disabled: 'disabled' } },
function linkFormat2(cellvalue, options, rowObject)
{
var linkUrl = '#Url.Action("GetMobilePhoneModels", "MobilePhoneModel", new { phonenumber = "Id" })'.replace('Id', rowObject['PhoneNumber']);
return '<span class="MobilePhoneModel">' + cellvalue + '</span>';
}
OR
function linkFormat2(cellvalue, options, rowObject)
{
var cellValueInt = parseInt(cellvalue);
if (cellValueInt = "mobile")
return "<img src='../../Content/Images/Devices/mobile.png' width='11px' height='20.75px' alt='" + cellvalue + "' title='" + cellvalue + "' />";
}
it works separatly, but not possible together.
Any help is appreciated. Thanks.
i solved it by combining, if somebody need:
function linkFormat2(cellvalue, options, rowObject) {
var cellValueInt = parseInt(cellvalue);
if (cellValueInt = "mobile")
{
var linkUrl = '#Url.Action("GetMobilePhoneModels", "MobilePhoneModel", new { phonenumber = "Id" })'.replace('Id', rowObject['PhoneNumber']);
return '<span class="MobilePhoneModel"><img src="../../Content/Images/Devices/mobile.png" width="11px" height="20.75px" alt="' + cellvalue + '" title="' + cellvalue + '" /></span>';
}
}
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
My .ascx page has two jqGrids
$(document).ready(function () {
var searchText = "";
$("#cclist").jqGrid({
//url: ResolveUrl() + '/CC_DoctorList',
datatype: 'local',
// postData: { "CaseNo": CaseNo },
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (jsondata) { return JSON.stringify(jsondata); },
jsonReader: { repeatitems: false, root: "d.rows", page: "d.page", total: "d.total", records: "d.records" },
colNames: ['Remove', 'DoctorID', 'Last Name', 'First Name', 'Address'],
colModel: [
{ name: 'RemoveAction', width: 80, fixed: true, sortable: false, resize: false, align: "center" },
{ name: 'ID', index: 'ID', width: 50, sortable: false, hidden: false },
{ name: 'LastName', index: 'LastName', width: 100, hidden: false, sortable: false },
{ name: 'FirstName', index: 'FirstName', width: 100, hidden: false, sortable: false },
{ name: 'Address', width: 420, hidden: false, sortable: false,
jsonmap: function (obj) {
var street = obj.Address.Address1
var city = obj.Address.City
var state = obj.Address.StateProvince
var zip = obj.Address.PostalCode
if (street != '') { street = street + ', ' }
if (city != '') { city = city + ', ' }
if (state != '') { state = state + ', ' }
var Address = street + city + state + zip
return Address
}
}
],
gridComplete: function () { addDeleteIcon(); },
pager: '#ccpager',
rowNum: 100,
rowList: [100, 200],
sortname: 'LastName',
sortorder: 'desc',
viewrecords: true,
gridview: true,
height: "100%",
caption: 'Send Copy of Report To:',
multiselect: false,
shrinkToFit: false,
loadui: "disabled"
})//.jqGrid('navGrid', '#ccpager', { edit: false, add: true, del: false, search: true });
$("#list").jqGrid({
url: ResolveUrl() + '/DoctorList',
datatype: 'local',
postData: { "searchText": searchText },
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (jsondata) { return JSON.stringify(jsondata); },
jsonReader: { repeatitems: false, root: "d.rows", page: "d.page", total: "d.total", records: "d.records" },
colNames: ['Add', 'DoctorID', 'Last Name', 'First Name', 'Address'],
colModel: [
{ name: 'AddAction', width: 80, fixed: true, sortable: false, resize: false, align: "center" },
{ name: 'ID', index: 'ID', width: 50, sortable: false, hidden: false },
{ name: 'LastName', index: 'LastName', width: 100, hidden: false, frozen: true, sortable: false },
{ name: 'FirstName', index: 'FirstName', width: 100, hidden: false, frozen: true, sortable: false },
{ name: 'Address', width: 420, hidden: false, sortable: false,
jsonmap: function (obj) {
var street = obj.Address.Address1
var city = obj.Address.City
var state = obj.Address.StateProvince
var zip = obj.Address.PostalCode
if (street != '') { street = street + ', ' }
if (city != '') { city = city + ', ' }
if (state != '') { state = state + ', ' }
var Address = street + city + state + zip
return Address
}
}],
gridComplete: function () {
var ids = jQuery("#list").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
var rd = $("#list").getRowData(cl);
var imageid = 'addImg_' + rd['ID']
be = "<div><image style='height:22px;width:20px;' alt='' src='" + ResolveUrl('//img/icons/add_black.png') + "'></image></div>"//"<input type='button' value='Remove' onclick=\"jQuery('#rowed2').editRow('" + cl + "');\" />";
jQuery("#list").jqGrid('setRowData', ids[i], { AddAction: be });
}
},
pager: '#pager',
rowNum: 5,
rowList: [5, 10, 15, 20],
sortname: 'LastName',
sortorder: 'desc',
viewrecords: true,
gridview: true,
caption: 'Search Result',
multiselect: false,
height: "100%",
shrinkToFit: false
})
jQuery("#list").click(function (e) {
var el = e.target;
if (el.nodeName !== "TD") {
el = $(el, this.rows).closest("td");
}
var iCol = $(el).index();
var row = $(el, this.rows).closest("tr.jqgrow");
var rowId = row[0].id;
var noMatch = 0;
if (iCol == 0) {
var rd = $("#list").getRowData(rowId);
var DoctorID = rd['ID'];
//check if the doc already exists in the cc doc list
var ids = jQuery("#cclist").jqGrid('getDataIDs');
if (ids.length == 0) {
ids.length = ids.length + 1;
}
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
var ccrd = $("#cclist").getRowData(cl);
var newrowid = ids.length + 1;
var ccDoctorID = ccrd['ID'];
if (DoctorID != ccDoctorID) {
noMatch = noMatch + 1;
if (noMatch == ids.length) {
var deleteImageIcon = "<div><image style='height:22px;width:20px;' alt='' src='" + ResolveUrl('//img/icons/trashbin.png') + "'></image></div>"; // onclick=\"jQuery('#cclist').delRowData('" + rowId + "');\"
jQuery("#cclist").jqGrid('addRowData', newrowid, { RemoveAction: deleteImageIcon, ID: rd['ID'], LastName: rd['LastName'], FirstName: rd['FirstName'], Number: rd['Number'], Address: rd['Address'] });
// alert(ids);
// var hdnids = document.getElementById('hdnDocIDs').value;
// hdnids.value = rd['ID'];
//var hdnids = jQuery("#<%=hdnDocIds.ClientID %>").val();
//alert(hdnids);
//hdnids = rd['ID'];
//alert('hdnvalue :' + hdnids);
//$("#<%=hdnlbldocs.ClientID%>").val(rd['ID'].toString() + ',' + $("#<%=hdnlbldocs.ClientID%>").val())
//$("#<%=hdnlbldocs.ClientID%>").val(rd['ID']);
//alert($("#<%=hdnlbldocs.ClientID%>").val());
//alert($("#<%=hdnlbldocs.ClientID%>").val(rd['ID'] + ','));
//alert($("#<%=hdnlbldocs.ClientID%>").val());
//jQuery("#<%=hdnDocIDs.ClientID %>").val(rd['ID']);
//The below works as expected - working.
jQuery("#<%=hdnDocIDs.ClientID %>").val(jQuery("#<%=hdnDocIDs.ClientID%>").val() + ',' + rd['ID']);
alert('All hdn ids : ' + jQuery("#<%=hdnDocIDs.ClientID%>").val());
//Using hidden fields it concatenates the doc ids - working
//alert('in side the for loop ID 2:' + rd['ID'] + ' DoctorID : ' + DoctorID);
//var furl = ResolveUrl() + '/AddCCDoctor';
//var furl = '';
//var param = '{"CaseNo":"' + CaseNo + '", "DoctorID":"' + DoctorID + '" }';
//var param = '{ "DoctorID":"' + DoctorID + '" }';
//var callback = function (msg) { dataHasChanged(); jQuery("#cclist").trigger("reloadGrid"); };
// ajaxJsonCall(furl, param, callback);
//jQuery("#cclist").jqGrid('setGridParam', {datatype: 'json'}).trigger('reloadGrid');
function (msg) { dataHasChanged(); jQuery("#cclist").trigger("reloadGrid"); };
}
}
}
}
});
The #list grid gets loaded by clicking on the Search button that I have not posted in the above code. Once the #list jqGrid is loaded users can click on the rows they are interested in and those rows are added to the #cclist jqgrid.
Now, to make the .ascx more generic I need to be able to write a public method in the code behind to return all the rows IDs (doctorIDs) that are added to the #cclist jqGrid and save the IDs to the database.
Can someone help me out on how to do this?
Thanks for taking time to read my post and posting your comments.
I put the code in a function as below and it is working as expected.
var hiddenField = $("#<%= hdnDocIDs.ClientID %>");
var selectedValues = "";
function updateSelectedRowsHidden() {
var selectedRows = [];
selectedRows = $('#cclist').jqGrid('getDataIDs');
selectedValues = "";
hiddenField.val("");
for (var i = 0; i < selectedRows.length; i++) {
var myRow = $('#cclist').jqGrid('getRowData', selectedRows[i]);
selectedValues = selectedValues + myRow.ID + ",";
}
hiddenField.val(selectedValues);
}
You see this answer, here I'm getting data out of selected rows and sending that to server method. Have a save button in your page like the one in answer
Now in your case you want data from entire grid. So for you code will be like this.
$('#clickMe').click(function() {
var rowsOnPage=[];
var docId=[];
rowsOnPage=$('#cclist').jqGrid('getDataIDs');
for(var i=0;i<rowsOnPage.length;i++)
{
docId.push(rowsOnPage[i].ID);
}
$.ajax({
type: 'POST',
url: '#Url.Action("editMe")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({DoctorID:docID })
dataType: "json",
success: function() {
$('#grid').trigger("reloadGrid");
},
error: function() {
alert("error");
}
});
});
and the server method(in ASP.NET MVC) which will be your code behind method in your approach will be like this.
//depends upon dataType of DoctorID(int or string)
public ActionResult editMe(string[] DoctorID)
{
}