This is my POST request:
$scope.TestPost = function (par1, par2) {
$http.post('EmployeeService.asmx/GetAllEmployees',
{
par1: par1,
par2: par2
})
.then(function (response) {
$scope.employees = response.data;
})
};
And this is code that gets called on the server side. Code is called correctly and json serialized object is written to response:
[WebMethod]
public void GetAllEmployees(string par1, string par2)
{
List<Employee> listEmployees = new List<Employee>();
string cs = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
List<Employee> _list = new List<Employee>();
SqlCommand cmd = new SqlCommand("SELECT * FROM tblEmployees", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
Employee emp = new Employee
{
id = Convert.ToInt32(rdr["Id"]),
name = rdr["Name"].ToString(),
gender = rdr["Gender"].ToString(),
salary = Convert.ToInt32(rdr["Salary"])
};
listEmployees.Add(emp);
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(listEmployees));
}
Response object is this - some strange line is appended at the end {"d":null} which I can not understand why. I am also receiving error on the client side: SyntaxError: Unexpected token:
"[{"id":1,"name":"Ben","gender":"Male","salary":55000},
{"id":2,"name":"Sara","gender":"Female","salary":68000},
{"id":3,"name":"Mark","gender":"Male","salary":57000},
{"id":4,"name":"Pam","gender":"Female","salary":53000},
{"id":5,"name":"Todd","gender":"Male","salary":60000}]{"d":null}"
Thanks to #82Tuskers and this post:
Differences between Response.End() and Response.Flush()
I've found the solution. I've changed code at the end of server side function to:
Context.Response.Clear();
Context.Response.Write(js.Serialize(listEmployees));
Context.Response.Flush();
Context.Response.End();
Response is now OK.
Related
I am using asp.net core. I need to display the data in the select dropdown in react from web api. WebApi GET method that returns SQL DataReader. Reader returns one row with prodid, prodname, and proddescr columns. Please help what the best way to write a get web api that uses SQL DataReader for filling the select dropdown in react.
[HttpGet("{ProductID}")]
public JsonResult GetProductInfo(int ProductID)
{
var response = GetProductInfo(ProductID);
return new JsonResult(response);
}
public string GetProductInfo(int Product_ID)
{
SqlConnection objConnect = new SqlConnection(_connectionString);
SqlCommand objCommand = new SqlCommand("usp_GetProdInfo", objConnect);
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.Parameters.Add(new SqlParameter("#Product_ID", SqlDbType.Int, 4));
objCommand.Parameters["#Product_ID"].Value = intProduct_ID;
string json = string.Empty;
List<object> objects = new List<object>();
objConnect.Open();
SqlDataReader reader = objCommand.ExecuteReader();
while (reader.Read())
{
IDictionary<string, object> record = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
record.Add(reader.GetName(i), reader[i]);
}
objects.Add(record);
}
json =JsonConvert.SerializeObject(objects);
reader.Close();
objConnect.Close();
return json;
}
you don't need to serialize data, Net can do it for you. And it is a very bad programming style to use objects instead of real classes. So return List instead of List
public ActionResult<List<Product>> GetProductInfo(int ProductID)
{
var response = GetProductInfoList(ProductID);
if (response != null) return Ok(result)
else retun BadRequest();
}
public List<Product> GetProductInfoList(int Product_ID)
{
List<Product> products = new List<Product>();
...fix the code to get typed List<Product> from reader
return products;
}
I have problem with reading json attribute even though object correctly instanced.
First, I send json from client side with JavaScript:
let object = {
firstName: document.getElementById("firstName").value,
lastName: document.getElementById("lastName").value,
username: document.getElementById("username").value,
password: document.getElementById("password").value,
email: document.getElementById("email").value,
action: "registration"
}
let request = new XMLHttpRequest();
...
On server side I have code:
req.setCharacterEncoding("UTF-8");
JSONObject jsonObject = null;
// String address = "/WEB-INF/pages/login.jsp";
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) {
/* report an error */ }
try {
jsonObject = HTTP.toJSONObject(jb.toString());
} catch (JSONException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
String action = jsonObject.getString("firstName");
jsonObject exists but program throws org.json.JSONException: JSONObject["firstName"] not found.
Object on server side when I use debugger:
There is no key with a name like firstName in your jsonObject. Instead, you need to search for Method property and then parse the firstName from it. First, declare a GetQueryMap method:
public static Map<String, String> GetQueryMap(String query)
{
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params)
{
String [] p=param.split("=");
String name = p[0];
if(p.length>1) {
String value = p[1];
map.put(name, value);
}
}
return map;
}
Then use it like:
String method = jsonObject.getString("Method");
Map params = GetQueryMap(method);
String firstName = (String)params.get("firstName");
String lastName = (String)params.get("lastName");
I think the issue is that you're not sending the data correctly from the browser side.
are you sending the correct content-type header (application/json)?
Are you serializing the object correctly for sending?
Am getting statuss 500 error.Am not getting exactly where am doing wrong.
When i click on getcustomer button 'Getcustomers' method is called which retuns json .
Script:
<script>
var MyApp = angular.module("MyApp", []);
MyApp.controller("ctrl", function ($scope, $http) {
$scope.helloAngular = "hello";
$scope.GetCustomers = function () {
debugger;
$http.get("/Home/Getcustomers")
.success(function (data) {
$scope.customerDetails = data;
}).
error(function (data, status, thrownError) {
//alert(status);
//alert(data.responseText);
alert(thrownError);
});
}
});
</script>
Server side code:
I get json data from this function:
public ActionResult Getcustomers()
{
string query = "select top 10 * from Customers ";
ArrayList custArray = new ArrayList();
SqlCommand cmd = new SqlCommand(query, sqlcon);
sqlcon.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
custArray.Add(new
{
Name = reader["ContactName"],
City = reader["City"],
PostalCode = reader["PostalCode"],
Country = reader["Country"],
Phone = reader["Phone"],
});
}
var result= JsonConvert.SerializeObject(custArray);
sqlcon.Close();
return Json(result);
}
I have search ,but cant get where am going wrong.Plz help me.
Yes, At last got what i was missing.
As status 500 is server error.It was occuring because the reader was not closed
after reading the sqldatareader(I really make silly mistakes)
public ActionResult Getcustomers()
{
string query = "select top 10 * from Customers ";
ArrayList custArray = new ArrayList();
SqlCommand cmd = new SqlCommand(query, sqlcon);
sqlcon.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
custArray.Add(new
{
Name = reader["ContactName"],
City = reader["City"],
PostalCode = reader["PostalCode"],
Country = reader["Country"],
Phone = reader["Phone"],
});
}
//Clean sqldatareader here;
reader.Close();
reader.Dispose();
var result= JsonConvert.SerializeObject(custArray);
sqlcon.Close();
return Json(result);
}
//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);
});
I have to convert this http post from JavaScript to Android.
I encountered a problem using cids: []. I can't create a jsonobject with this symbol [ ]. It should be an empty array.
This is my JavaScript:
var makeAjaxRequest = function () {
Ext.getBody().mask('Loading...', 'x-mask-loading', false);
var obj = {
uid: 1161,
cids: []
};
Ext.Ajax.request({
url: 'http://test.com.my',
method: 'POST',
params: { json: Ext.encode(obj) },
success: function (response, opts) {
Ext.getCmp('content').update(response.responseText);
Ext.getCmp('status').setTitle('Static test.json file loaded');
Ext.getBody().unmask();
var data = Ext.decode(response.responseText);
Ext.Msg.alert('result::', data.r[1].id, Ext.emptyFn);
}
});
};
This is my Android code:
String[] temp = null;
JSONObject json = new JSONObject();
HttpPost post = new HttpPost(url);
json.put("uid", 1161);
json.put("cids", temp);
List postParams = new ArrayList();
postParams.add(new BasicNameValuePair("json", json.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
tv1.setText(postParams.toString());
post.setEntity(entity);
post.setHeader("Accept", "application/json");
response = client.execute(post);
Using String[] temp = null; isn't right.
Use String[] temp = {};. That denotes an empty array.
I cant create a jsonobject with this symbol "[ ]".
^^That's basically a JSON Array you are trying to create. JSONObjects have {} and JSONArrays have [].
public void writeJSON() {
JSONObject user = new JSONObject();
JSONObject user2;
user2 = new JSONObject();
try {
user.put("dish_id", "1");
user.put("dish_custom", "2");
user.put("quantity", "2");
user.put("shared", "2");
user2.put("dish_id", "2");
user2.put("dish_custom", "2");
user2.put("quantity", "4");
user2.put("shared", "3");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray notebookUsers = new JSONArray();
notebookUsers.put(user);
notebookUsers.put(user2);
System.out.println("the JSON ARRAY is"+notebookUsers);
Will give a JSON array of user and user2 with symbols "[]"