How To Call Json API from C# Useing Javascript - javascript

I made this Web API Apllication Using ASP.NET und C#
and output response from this API is Json object To can in java script Application Call this API with Ajax
this is C# Code :
public string Get()
{
string Sql3 = "(SELECT top 10 Raspberry_ID, Raspberry_name, Speaker_Name, currently_playing_song,Speaker_Volume,Speaker_Availability, Speaker_Mute,Date_Time,Speaker_Status, Row_Number() over (order by Date_Time desc) as RowNumber FROM Raspi_speaker)T";
string Sql2 = "Speaker_Volume, Speaker_Status, Speaker_Availability, Speaker_Mute, Date_Time, RowNumber FROM";
string Sql = "SELECT top 10 Raspberry_ID, Raspberry_name, Speaker_Name, currently_playing_song," + Sql2 + Sql3;
SqlDataAdapter adap = new SqlDataAdapter(Sql, conn);
string[] Result = new string[10];
DataTable dataTable = new DataTable();
adap.Fill(dataTable);
int i = 0;
foreach (DataRow dataR in dataTable.Rows)
{
string Val;
Val = Convert.ToString(dataR["Raspberry_name"]);
Result[i] = Val;
i++;
}
Object[] obj = {
new { RasspiName = Result}
};
if (dataTable.Rows.Count > 0)
{
return JsonConvert.SerializeObject(obj);
}
return "No Data Found";
}
}
and output is this Json Object:
[{"RasspiName":["Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Trais-Sonos-Pi","Trais-Sonos-Pi","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS"]}]
JavaScript Code is:
function Ajax(){
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState == 4 && (request.status == 200)) {
var DataR = [];
DataR =JSON.parse(request.responseText)
console.log(DataR)
}
}
var url = 'http://localhost:41839/api/Musik';
request.open('GET',url ,true);
request.send()
}
My problem is that it treats the Json object as text Although I used ((JSON.parse)) Method in Java Script ... For example when I write (( console.log(DataR[ 0 ])) I get only one Letter for Example [ Instead of Value when I write (( console.log(DataR[ 0 ].RasspiName)) I get Undefined
I dont know if proplem from C# code oder From Java Script
I hope your help thanks so much

I don't understand how you defined the API Get method in the back-end code example, but I think you should set something like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public string GetDashboardInfo()
{
//your code here
}
You can use Ajax to make the GET request:
function GetData() {
try {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:41839/api/Musik",
data: '',
dataType: "json",
success: OnSuccessGetData,
error: OnErrorGetData
});
}
catch (ex) {
console.log("GetData(): " + ex.toString());
}
}
function OnSuccessGetData(result) {
try {
if (result.d !== "" && result.d !== null) {
var dataSourceJson = JSON.parse(result.d);
}
else {
console.log("OnSuccessGetData: result is null!");
}
}
catch (ex) {
console.log("OnSuccessGetData(): " + ex.toString());
}
}
function OnErrorGetData(httpRequest, textStatus, errorThrown) {
try {
console.log("OnErrorGetDashboardData: " + textStatus + " " + errorThrown + " " + httpRequest);
}
catch (ex) {
console.log("OnErrorGetDashboardData(): " + ex.toString());
}
}
More about JavaScript Get request here.

Related

Alternative to window.location.href using POST request - ASP.NET MVC

I am writing below code in Javascript to retrieve comment and navigating same page after repopulating the data
function MoveItem() {
var empId = document.getElementById('EMP_ID').value;
var commentValue = $("#RESPONSE").val();
if ($.trim(commentToSave).length > 0) {
showAjaxLoading();
var empData= "APPROVE";
var baseControllerUrl = '/Employee/EmpManagement/PushItem';
window.location.href = baseControllerUrl + "/" + empId + "?comment=" + commentValue + "&empData=" + empData + "&currentItem=" + itemData;
} else {
aet('Pelase enter comments', 'E');
}
}
In controller the method written as
[HttpGet]
public async Task<ActionResult> MoveItem(int id, string comment, string decision, string currentworkflow)
{
return RedirectToAction("EditEmpManagemnt", "EmpManagement", new { id = id });
}
I want to convert MoveItem action method to a [HttpPost] type and what all changes are needed in Javascript & action method ? Can anyone explain with a sample code.
You can send a POST request using the fetch method. We send the data with the JSON format. Replace your javascript with this:
function MoveItem() {
var empId = document.getElementById('EMP_ID').value;
var commentValue = $("#RESPONSE").val();
if ($.trim(commentToSave).length > 0) {
showAjaxLoading();
var empData = "APPROVE";
var baseControllerUrl = '/Employee/EmpManagement/PushItem';
var url = baseControllerUrl + "/" + empId;
//here we put the url as a first parameter
//then we configure the http method
//and in the body we pass in the object in JSON format
fetch(url, {
method: "POST",
body: JSON.stringify({
"comment": commentValue,
"empData": empData,
"currentItem": itemData
})
}).then(result => {
//do something with the result you get back
console.log("Completed with result: " + result);
}).catch(err => {
//if any error occured, then show it here
console.log("There is an error: " + err);
});
} else {
aet('Please enter comments', 'E');
}
}
And in your C# code just replace [HttpGet] attribute with [HttpPost]

IIS connections overload and CPU running high

We have an MVC 5 website hosted by iis on our server but we are experiencing the following problem with one of the functionalities in the website.
We have a datatable that gets populated with data from a SQL database. For each record a checkbox gets created for users to check and link that record. Once the record is checked and linked, that specific record is stored in a link table. Please see the code bellow for this functionality. For each record I call a method on the server side and that executes the stored proc.
javascript
$("#btnLinkTest").click(function () {
var counter = 0;
var checked_checkboxCounter = 0;
$('#counter').text("0 linked");
$('#linkModal').modal('show');
var oTable = $("#StudentListTable").dataTable();
$(".cbxLink:checked", oTable.fnGetNodes()).each(function () {
checked_checkboxCounter = checked_checkboxCounter + 1;
var currentRow = $(this).closest("tr");
var data = $('#StudentListTable').DataTable().row(currentRow).data();
var ER, AC;
var StudentID = data['StudentID'];
var TestID = $('#lblGradeID').html();
var ET = $(this).closest('tr').find(".extraTime").val();
if ($(this).closest('tr').find(".cbxER").is(':checked')) {
ER = "True";
} else {
ER = "False";
}
if ($(this).closest('tr').find(".cbxAC").is(':checked')) {
AC = "True";
} else {
AC = "False";
}
var jsObject =
{
StudentID: StudentID,
TestID: TestID,
ModifiedBy: "1",
ElectronicReader: ER,
Accomodation: AC,
StudentExtraTime: ET
};
$.ajax({
type: "POST",
url: "/Administration/LinkTestToStudent_Ins/",
data: JSON.stringify(jsObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
counter = counter + 1;
$('#counter').text(counter + " / " + checked_checkboxCounter );
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
return false;
});
c#
public string LinkTestToStudent_Ins(string StudentID, string TestID, string ModifiedBy, string ElectronicReader, string Accomodation, string StudentExtraTime)
{
string result;
DataBaseConnection dbConn = new DataBaseConnection();
using (SqlConnection con = dbConn.SqlConn())
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("StudentTestLink_ins", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#StudentID", StudentID);
cmd.Parameters.AddWithValue("#TestID", TestID);
cmd.Parameters.AddWithValue("#ModifiedBy", HttpContext.Current.Session["UserID"]);
cmd.ExecuteNonQuery();
con.Close();
return result = "Linked";
}
catch (Exception ex)
{
return "Connection Error";
}
}
}
The problem is if we link over a 100 records for example, the connections on the server goes up a lot (so 100 in this case) and the cpu runs at almost 100% because of the IIS Worker. I suspect that this is happening because the javascript code calls the c# all at once for all checked records.
Please advise how I can optimize this code so that I do not get the above mentioned problem. Possibly I can call the c# method one at a time and not all at once.

Ajax Call to Service with Multiple Return Values

I am building a WCF service in C# in which I would like to be able to return multiple values from some of my functions. The code below appears to do this:
[WebMethod]
public void ReturnMultipleValues(int startingValue)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
var jsonData = new { FirstValue = startingValue, SecondValue = startingValue * 2 };
Context.Response.Write(ser.Serialize(jsonData));
}
I am trying to access this function through an ajax call in JavaScript code:
function runTestService() {
$.ajax({
type: "POST",
url: "http://localhost:12345/WebServices/MyService.asmx/ReturnMultipleValues",
contentType: "application/json;charset=utf-8",
data: "{ 'startingValue' : 6 }",
dataType: "json",
done: function(data) {
var firstValue = data.FirstValue;
var secondValue = data.SecondValue;
alert("First: " + firstValue + ", Second: " + secondValue);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
}
When I execute the above JavaScript code, the function in the .done portion never executes. When I check Fiddler, however, I see that the function in my service did execute properly and returned the correct values in the JSON.
Is there another way I should code either the service or the ajax call to it?
You are not supposed to write to Context.Response by yourself. Just return an object from method and let the framework do it for you
[WebMethod]
public object ReturnMultipleValues(int startingValue)
{
var jsonData = new { FirstValue = startingValue, SecondValue = startingValue * 2 };
return jsonData;
}
And you have to consider the fact web service wraps json repsonse in object with d property
{
"d": {
"FirstValue": 6,
"SecondValue": 12
}
}
So update js as well
done(function (data) {
data = data.d;
var firstValue = data.FirstValue;
var secondValue = data.SecondValue;
alert("First: " + firstValue + ", Second: " + secondValue);
});

Ajax call to webmethod gives ERROR 500

I'm a beginner and I want to use ajax to load some data from database to dropdownlist when another dropdownlist selected index in changed
but I'm getting nothing but 500 error
My jquery ajax code
function ddlGroups() {
var s = $("#Content_ddlGroups").find("option:selected").prop("value");
$.ajax({
method: "GET",
contentType: "application/json; charset=utf-8",
//url is the path of our web method (Page name/function name)
url: "../panels/admin/AddProject.aspx/getSubgroups",
data: { Id: s },
dataType: "json",
//called on jquery ajax call success
success: function (result) {
$('#Content_SubGroups').empty();
$.each(result.d, function (key, value) {
$("#Content_ddlGroups").append($("<option></option>").val(value.GroupID).html(value.Title));
});
},
//called on jquery ajax call failure
error: function ajaxError(result) {
alert(result.status + ' : ' + result.statusText);
}
});
};
and my c# code
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<Group> getSubgroups(string Id)
{
DataTable dt = new DataTable();
List<Group> objDept = new List<Group>();
GroupsRepository jg = new GroupsRepository();
//Page page = (Page)HttpContext.Current.Handler;
//DropDownList DDLGroups = (DropDownList)page.FindControl("DDLGroups");
dt = jg.LoadSubGroup(Id.ToInt());
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
objDept.Add(new Group
{
GroupID = Convert.ToInt32(dt.Rows[i][0]),
Title = dt.Rows[i][1].ToString(),
});
}
}
return objDept;
}
What is the problem??
The jQuery is not the problem here. The 500 error is thrown by the server, so you should review the log of your c# code to find out the details about it and be able to narrow the causes.
In your AJAX Call actually 500 error caused beacuse you have passed
Id:s instead of Id having some digits. Ex. Id : 5.
I see your code if you passed string as a id so in your server side method
you are trying to convert that string to int.That actually causes the 500 error.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<Group> getSubgroups(string Id)
{
DataTable dt = new DataTable();
List<Group> objDept = new List<Group>();
GroupsRepository jg = new GroupsRepository();
//Page page = (Page)HttpContext.Current.Handler;
//DropDownList DDLGroups = (DropDownList)page.FindControl("DDLGroups");
dt = jg.LoadSubGroup(Id.ToInt()); // Here You have convert string to Int that's why you got 500 Error.
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
objDept.Add(new Group
{
GroupID = Convert.ToInt32(dt.Rows[i][0]),
Title = dt.Rows[i][1].ToString(),
});
}
}
return objDept;
}

how to know in wcf service in key/value pair

//IService.cs
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
String CheckAuth(String AccountID, String Password);
//Service.cs
public String CheckAuth(String AccountID, String Password)
{
String message="";
string StrCon = #"my conn string";
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(StrCon);
string qry = "select * from Account where AccountID='" + AccountID + "' and Password='"+Password+"'";
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
message = "Authorized";
}
else
{
message = "unauthorized";
}
con.Close();
return message;
}
i want to know that what does the variable d: stands for and how can i change the d: to Message:..??
i need some suggestion thank you..
//GETTING output
{
d: "Authorized"
}
//expected output
{
Message: "Authorized"
}
i m new to wcf so it will be helpful if i get undertandable suggestion
thank you..
The variable d is there for security reasons.
But you can always return an object instead of a string
public object CheckAuth(String AccountID, String Password)
{
// .. snip
return new {
Message = message
};
}
If you call your service like this, it should return something like
{
"d" : {
"Message": "Authorized"
}
}
Not sure what you're using on the front-end, if you use jQuery you could make a wrapper around the ajax function:
function doAjax(url, data, cb) {
$.ajax({
url: url,
data: data,
success: function(data) {
cb(data.d);
}
});
}
and make use of your new defined function like this:
doAjax('/CheckAuth', yourDataObj, function result(data) {
console.log(data.Message);
});

Categories

Resources