Webservice
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Colaborador GetUserInfo(int idColaborador)
{
bool Flag = true;
string constr = ConfigurationManager.ConnectionStrings["ControloInterno_ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string[] Procedure = new string[] { "spOperadores", "spDetalhesColaborador", "spRegDrives" };
string[] ActionParams = new string[] { "SELECTINF", "SELECTUSR", "SELECTID" };
Colaborador co = new Colaborador();
Detalhes dt = new Detalhes();
Acesso ac = new Acesso();
for (int i = 0; Flag; i++)
{
using (SqlCommand cmd = new SqlCommand(Procedure[i]))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", ActionParams[i]);
cmd.Parameters.AddWithValue("#idColaborador", idColaborador);
cmd.Connection = con;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (Procedure[i] == "spOperadores")
{
while (rdr.Read())
{
co.Name = rdr["Nome"].ToString();
co.Department = rdr["Departamento"].ToString();
co.Profile = rdr["DescricaoPerfil"].ToString();
co.Name = rdr["Nome"].ToString();
co.Department = rdr["Departamento"].ToString();
co.Profile = rdr["DescricaoPerfil"].ToString();
co.AdminDate = rdr["dataadmin"].ToString();
co.Phone = rdr["tele"].ToString();
co.Status = rdr["status"].ToString();
co.Observations = rdr["Observacoes"].ToString();
co.CreationDate = rdr["DataCriacao"].ToString();
co.AltDate = rdr["AltData"].ToString();
co.Creator = rdr["criador"].ToString();
}
rdr.Close();
}
else if (Procedure[i] == "spDetalhesColaborador")
{
while (rdr.Read())
{
co.Detalhes = dt;
co.Detalhes.Description = rdr["Descricao"].ToString();
co.Detalhes.Value = rdr["Value"].ToString();
}
rdr.Close();
}
else if (Procedure[i] == "spRegDrives")
{
while (rdr.Read())
{
co.Acesso = ac;
co.Acesso.drive = rdr["Drive"].ToString();
co.Acesso.tipoAcesso = rdr["TipoAcesso"].ToString();
co.Acesso.nivel = rdr["nivel"].ToString();
Flag = false;
}
rdr.Close();
}
cmd.Parameters.Clear(); // Clear SQLCommand Parameters
con.Close();
}
}
return co;
}
}
and AJAX call
$(document).ready(function () {
$('#AdminUserNameModal').on('shown.bs.modal', function () {
var url = "GetColaboradoresWebService.asmx/GetUserInfo";
var ID = "15";
$("#UserInfoPanel").html("<div style='text-align:center; border:1px solid red; padding:3px; width:200px'>Please Wait...</div>");
var request = $.ajax({
type: "POST",
url: url,
data: ID,
contentType: "application/json; charset-utf-8",
dataType: "json"
});
request.done(function (data) {
console.log(data);
var TableContent = "<table class='table table-bordered table-striped'>";
for (var i = 0; i < data.d.length; i++) {
TableContent += "<tr>" +
"<td>" + data.d[i].Name + "</td>" +
"<td>" + data.d[i].Detalhes.Description + "</td>" +
"</tr>";
"<tr>" +
"<td>" + data.d[i].Name + "</td>" +
"<td>" + data.d[i].Detalhes.Description + "</td>" +
"</tr>";
"<tr>" +
"<td>" + data.d[i].Name + "</td>" +
"<td>" + data.d[i].Detalhes.Description + "</td>" +
"</tr>";
}
TableContent += "</table>";
$("#UserInfoPanel").html(TableContent);
});
request.fail(function (data) {
console.log(data);
});
})});
I already searched everywhere and couldn't find anything that solved my problem. I tried recieve a string too and nothing. I keep getting conversion to int or string errors, I don't understand, I'm trying to send a string and recieve a string, or int to int and still gives me an error? In the code I'm sending a string and recieving an int but i was just changing the code again.
Problem solved, the correct way was to treat everything as a string like this++
data: "{idColaborador: " + idColaborador + " }",
var idColaborador = 15
try this instead , why are you sending a string to a method that accepts an int as a parameter ?
Edit :
your property names must match the name of the parameter on the method so they can be bound appropriately like i changed above , this will work
data:{idColaborador:ID}
Related
I am currently trying to check if a value of a string variable is "Apple". Now I need to pass a list of fruits to javascript from C#.
C# Code
List<String> fruits = new List<String>{"Apple","Mango","Orange"}
JavaScript Code
$(document).on('click','#dvAppContent input:checkbox[id*=chkfunction]', function () {
ToggleApplication(this);
});
function ToggleApplication(currentFunction) {
var fruitName = $(currentFunction).closest('ui').parent('label').text().trim();
If(fruitName == "Apple")
{
return true;
}
}
Use Ajax call in JavaScript.
Something like this:
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/api/StudentAPI/GetAllStudents",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//alert(JSON.stringify(data));
$("#DIV").html('');
var DIV = '';
$.each(data, function (i, item) {
var rows = "<tr>" +
"<td id='RegdNo'>" + item.regNo + "</td>" +
"<td id='Name'>" + item.name + "</td>" +
"<td id='Address'>" + item.address + "</td>" +
"<td id='PhoneNo'>" + item.phoneNo + "</td>" +
"<td id='AdmissionDate'>" + Date(item.admissionDate,
"dd-MM-yyyy") + "</td>" +
"</tr>";
$('#Table').append(rows);
}); //End of foreach Loop
console.log(data);
}, //End of AJAX Success function
failure: function (data) {
alert(data.responseText);
}, //End of AJAX failure function
error: function (data) {
alert(data.responseText);
} //End of AJAX error function
});
});
</script>
And in the backend in c#, something like this:
public class StudentAPIController : Controller
{
// GET: api/GetAllStudents
[HttpGet]
public IEnumerable<PersonalDetail> GetAllStudents()
{
List<PersonalDetail> students = new List<PersonalDetail>
{
new PersonalDetail{
RegNo = "2017-0001",
Name = "Nishan",
Address = "Kathmandu",
PhoneNo = "9849845061",
AdmissionDate = DateTime.Now
},
new PersonalDetail{
RegNo = "2017-0002",
Name = "Namrata Rai",
Address = "Bhaktapur",
PhoneNo = "9849845062",
AdmissionDate = DateTime.Now
},
};
return students;
}
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table =
"<tr><th>Title</th><th>Author</th><th>Cover Page</th><th>Ratings</th></tr>";
var x = xmlDoc.getElementsByTagName("best_book");
for (i = 0; i < x.length; i++) {
bookname = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
authorname = x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
table +=
"<tr><td class='book'>" +
bookname +
"</td><td class='author'>" +
authorname +
"</td><td>" +
"<img src='" +
x[i].getElementsByTagName("image_url")[0].childNodes[0].nodeValue +
"' height='100px' width='70px'>" +
"</td><td>" +
"<div class='stars' data-rating='1'>" +
"<span class='star'> </span>" +
"<span class='star'> </span>" +
"<span class='star'> </span>" +
"<span class='star'> </span>" +
"<span class='star'> </span>" +
"<input type='button' value='Add Rating' onClick = 'submitRating()'>" +
"</div>" +
"</td></tr>";
console.log(bookname);
}
document.getElementById("result").innerHTML = table;
}
async function submitRating() {
try {
let boo = bookname;
console.log(boo);
let auth = authorname;
console.log(auth);
let rat = 5;
console.log(rat);
let data = JSON.stringify({
author: auth,
book: boo,
rating: rat
});
console.log(data);
let res = await fetch(hostUrl + "api/ratings", {
method: "POST",
body: data,
headers: {
"Content-Type": "application/json"
}
});
console.log(res);
res.json().then(matter => {
console.log(matter);
});
// let myJson = res.json();
// console.log(myJson);
if (res.status == 200) {
console.log("the status is " + res.status);
} else {
console.log("the status is " + res.status);
alert("rating not given");
}
} catch (error) {
console.log("Error:" + error);
}
}
I am trying to call submitRating function on every iteration of for loop,
but I am not getting the correct method for this in JavaScript.
Right now, after running the loop, onclick = submitRating() function only submitting the last value in mongodb.
Can someone help me with this please?
That is because the bookname and authorname retain the last value set by the final iteration of the for loop. In other words, these variables are simply overwritten multiple times until the for loop ends. If you want to store these information on a per-item basis, you can store them in HTML5 data- attributes and retrieve them in the onclick handler.
For example, you can do this:
"<input type='button' value='Add Rating' data-bookname='"+bookname+"' data-authorname='"+authorname+"' onClick='submitRating(this)' />"
And then, in your submitRating method, you can simply read the information using Element.dataset:
async function submitRating(el) {
const bookname = el.dataset.bookname;
const authorname = el.dataset.authorname;
// More logic here
}
I have an html table on my webpage that is displaying data that I am pulling from a MySql database. When a user clicks on one of the table rows, depending on the data in the row, another div on the page is supposed to update displaying other information. The problem is, when I try to update the inner html of the div from my c# code-behind page, nothing happens. No errors in the dev console, no exceptions thrown, nothing. Why is this happening and how can I fix it? What am I doing wrong?
HTML table data that is being produced through c# code:
protected void PopulateUsers(bool active)
{
ArrayList userList = new ArrayList();
Query query = new Query();
StringBuilder userListHTML2 = new StringBuilder();
string userListHTML = "" +
"<table runat=\"server\" id=\"userListTable\" class=\"table table-striped table-bordered table-hover\">" +
"<thead>" +
"<tr>" +
"<th>User ID</th>" +
"<th>Name</th>" +
"<th>E-Mail</th>" +
"<th>Phone</th>" +
"<th>IsActive</th>" +
"</tr>" +
"</thead>" +
"<tbody>";
string userListHTML3 = "" +
"</tbody>" +
"</table>";
switch (active)
{
case true:
userList = query.GetUserList(true);
break;
case false:
userList = query.GetUserList(false);
break;
}
foreach (User user in userList)
{
userListHTML2.Append(string.Format(#"
<tr>
<td>{0}</td>
<td>{1}</td>
<td>{2}</td>
<td>{3}</td>
<td>{4}</td>
</tr>", user.userID, user.displayName, user.email, user.phone, user.isActive));
}
userListDiv.InnerHtml = userListHTML + userListHTML2 + userListHTML3;
}
jQuery/javascript code capturing click:
function viewUserSpecifics(id) {
var data = id;
var xmlHttpRequest;
xmlHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("testing.XMLHTTP");
if (xmlHttpRequest == null) {
alert("ajax not supported");
return null;
}
xmlHttpRequest.open("GET", "ManagerPopup.aspx?ID=" + data, true);
xmlHttpRequest.send(null);
//document.getElementById('userDataDiv').innerHTML.
}
$(document).ready(function () {
$('#userListTable tbody').on('click', 'tr', function () {
var tableData = $(this).children("td").map(function () {
return $(this).text();
}).get();
//$("#< %= userIDHidden.ClientID %>").val($.trim(tableData[0]));
//alert($.trim(tableData[0]));
viewUserSpecifics($.trim(tableData[0]));
return false;
});
});
Receiving the http request:
protected void Page_Load(object sender, EventArgs e)
{
PopulateUsers(true);
if (Request.QueryString["ID"] != null)
{
string ID = Request.QueryString["ID"];
SpecificUser(ID);
}
}
Method that is supposed to be updating div inner html:
protected void SpecificUser(string id)
{
System.Windows.Forms.MessageBox.Show(id);
Query query = new Query();
User specificUser = new User();
specificUser = query.GetUserSpecifics(Convert.ToInt32(id));
string newFormRow = "<div runat=\"server\" class=\"form-row\">";
string newFormGroup = "<div runat=\"server\" class=\"form-group\">";
string newFormGroupCol = "<div runat=\"server\" class=\"form-group col-md-6\">";
string closeDiv = "</div>";
string UserDataHTML1 = string.Format("" +
newFormRow +
"<label id=\"userIDLabel1\">User ID:</label>" +
"<label id=\"userIDLabel2\">{0}</label>" +
closeDiv +
newFormRow +
newFormGroupCol +
"<label id=\"lblFName\" for=\"txtFName\">First Name: </label>" +
"<input id=\"txtFName\" class=\"form-control\" runat=\"server\" type=\"text\" value={1} />" +
closeDiv +
newFormGroupCol +
"<label id=\"lblLName\" for=\"txtLName\">Last Name: </label>" +
"<input id=\"txtFName\" class=\"form-control\" runat=\"server\" type=\"text\" value={2} />" +
closeDiv +
closeDiv, id, specificUser.fName, specificUser.lName);
userDataDiv.InnerHtml = UserDataHTML1;
}
Any help would be greatly appreciated! Thanks!
To update the html content you should send back a response from your C# route to the client, and update the html part by using jQuery with received data
I've got a JavaScript file which is querying a SharePoint list. I'm querying two drop down lists. The first - LifeCycleStatus - comes back fine, but the Priority drop down comes back with screen grab [object OBJECT]. I think it has to do with the var query string. I've added the 'Priority' column to the var query but it doesn't seem to be making any difference
var query = "http://collaboration-
de.vxxx.com/sites/it/SystemInventory/_vti_bin/listdata.svc/Devices?$expand=LifeCycleStatus&Priority&$filter=Id eq " + window.DeviceId + "";
Full JavaScript below:
function getDeviceDetails() {
var txtTitle = "";
var txtOverview = "";
var txtAccessories = "";
var txtDevicetype = "";
var txtTypicalDeviceUsage ="";
var txtKnownSystemIssues ="";
var txtLifeCycles = "";
var txtTrafficlight = "";
var tempLCS2 = "";
var query = "http://collaboration-dev.xxx/sites/it/SystemInventory/_vti_bin/listdata.svc/Devices?$expand=LifeCycleStatus&Priority&$filter=Id eq " + window.DeviceId + "";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function(index, item) {
var tempID = item.Id;
var tempTitle = item.Title;
var LifeCycleStart = item.DeviceAvailableFrom;
var LifeCycleStatus = item.LifeCycleStatusValue;
var DeviceOverView = item.Description;
var AccessDetails = item.Accessories;
var DeviceKind = item.Devicetype;
var Usage = item.TypicalUsage;
var DevicePriority = item.Priority;
txtTitle = "<p>" + LifeCycleStart + "</p><p>" + LifeCycleStatus + "</p>";
txtOverview = "<p>" + DeviceOverView + "</p>";
txtAccessories = "<p>" + AccessDetails + "</p>";
txtDevicetype = "<p>" + DeviceKind + "</p>";
txtTypicalDeviceUsage = "<p>" + Usage + "</p>";
txtTrafficlight = "<p>" + DevicePriority + "</p>";
// txtKnownSystemIssues = "<p>" + KnownSystem + "</p>"
});
$('#devicedetails').append($(txtTitle));
$('#deviceoverview').append($(txtOverview));
$('#devicekind').append(txtDevicetype);
$('#deviceacc').append(txtAccessories);
$('#deviceuse').append(txtTypicalDeviceUsage);
$('#devicestatus').append(txtTrafficlight);
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}
"Priority" and "LifeCycleStatus" contains an object. You can use the debugger/console to see what the object is - I bet it contains a string with the Value, and the internal ID of the value, possibly other things. Converting an object to a string returns "[object Object]".
"PriorityValue" and "LifeCycleStatusValue" are probably shorthands to the value string.
I need to set href to Javascript function. When I click it, nothing happens, but when I hover over link it displays:
unsafe:javascript:ShowManagementdDiv('65','a60f2a16-267e-418d-bb14-d88de3a33b5f','0');
The table data is built dynamically in my angular controller:
contractorService.getemrtabulation()
.success(function (data) {
$scope.emrcolumns = data.EMRTabulationColumns;
repeatRow = '<td align="center" valign="middle" style="background-color:Transparent;border-color:Black;border-width:1px;border-style:Solid;padding:5px;white-space:nowrap;"><a class="IncidentColumn" ng-href={{e.hyper}}>Click Here to Review EMR Document</a></td>';
firstRow = '<td>EMR Document</td>';
for (i = 0; i < $scope.emrcolumns.length; i++) {
repeatRow = repeatRow + '<td>{{e.' + $scope.emrcolumns[i].vchAssociatedDetailColumn + '}}</td>';
firstRow = firstRow + '<td>' + $scope.emrcolumns[i].vchColumnHeaderText + '</td>'
}
firstRow = '<tr>' + firstRow + '</tr>';
$scope.emrdetail = data.EMRTabulationDetail;
angular.forEach($scope.emrdetail, function (value, key) {
value.dteExpirationDate = convertDate(value.dteExpirationDate);
value.dteDateCompleted = convertDate(value.dteDateCompleted);
value.dteEffectiveDate = convertDate(value.dteEffectiveDate);
});
angular.forEach($scope.emrdetail, function (value, key) {
contractorService.getimage(value.EMRDetailID, value.dteEffectiveDate)
.success(function (data) {
$scope.emrdetail[key].hyper = data;
});
});
$scope.emrTable = '<table>' + firstRow + '<tr style="text-align:center" ng-repeat="e in emrdetail">' + repeatRow + '</tr></table>';
firstRow = '';
repeatRow = '';
});
I use this to call it in the html:
<div class="row row-relative">
<div class="col-md-12">
<div>{{emrQuestion.EMRTabulationID}}{{emrQuestion.vchTabulationSequenceLetter}}. {{emrQuestion.vchClassPropertyName}}</div><br />
<div dynamic="emrTable"></div><br /><br />
</div>
</div>
The function is in a <script> tag on the page:
function ShowManagementdDiv(imageTypeID, Guid, selectedYear) {
var TargetWidth = 950;
var TargetHeight = 670;
bModalPopupActivated = true; window.clearTimeout(t);
DisplayModalDivExitWithClickSave('box', TargetWidth, TargetHeight, 'http://localhost/PECIMS/DocumentManagement.aspx?eid=' + imageTypeID + '&Edx=' + Guid + '&y=' + selectedYear, 'Close', 'Click to close window. ');
}
Here is the C# code that creates the link:
public async Task<ActionResult> GetImage(int emrDetailID, string docDate)
{
var columns = await CommonClient.GetEMRTabulationColumnsForClusterID(876);
var getcolumn = columns.FirstOrDefault(c => c.EMRTabulationColumnID == 1);
int? imageTypeId = getcolumn.EdataFileImageTypeID;
UserInfo.intDocumentManagementMode = 13;
UserInfo.intPerspectiveCompanyID = UserInfo.intMajorID;
UserInfo.intPerspectiveCompanyTypeID = UserInfo.intMajorCompanyType;
UserInfo.SegmentID = emrDetailID;
UserInfo.dteDocumentDate = DateTime.Parse(docDate);
var token = await CompanyClient.SaveRecallData(UserInfo);
string strPathAndQuery = Request.Url.PathAndQuery;
string strUrl = Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");
string LinkToImagesApp = "";
LinkToImagesApp = AppendProtocolAndHostHeadersPathToWebConfigPath("LinkToImagesApplication");
string javaLink = strUrl + LinkToImagesApp + "/DocumentManagement.aspx?eid=";
string docLink;
string address = "javascript:ShowManagementdDiv('" + imageTypeId + "','" + token + "','0');";
return Json(address, JsonRequestBehavior.AllowGet);
}
I am assuming that the issue is that Angular deems the Javascript as "unsafe". Any assistance is greatly appreciated.
In order to use the Javascript function in my href I had to add the following to my app.js file:
app.config([
'$compileProvider',
function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|javascript):/);
}
]);