//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);
});
Related
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.
I have a problem whereby I would like to pass a json string as a field value but I keep getting "The input was not valid". So to be clear I have an object in my front end that I use the below to pass to my API:
let j: Settings = {} as Settings;
j.user_settings_ID = object.user_settings_ID;
j.user_ID = object.user_ID;
j.user_filter = JSON.stringify(object.user_filter);
j.user_test_filter = JSON.stringify(object.user_test_filter);
fetch('api/Profile/UpdateProfileSettings/?id=' + object.user_settings_ID, {
method: 'put',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Authorization': 'Bearer ' + sessionStorage.getItem('token')
},
body: "'" + JSON.stringify(j) + "'",
}).then(data => {
if (!data.ok) {
alert("Failed");
}
}).catch((ex) => {
alert("Failed");
});
In my API I have:
[HttpPut("[action]")]
public async Task<string> UpdateProfileSettings(int id, [FromBody] string obj)
{
HttpClient clientRoute = new HttpClient();
var response = await clientRoute.PutAsync("https://something.com/api/UserSettings/put/" + id, new StringContent(obj, Encoding.UTF8, "application/json"));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
I don't have a problem when I set the j.user_filter and j.user_test_filter with any normal string, but I would like to put the 'jsonified' string as the value for the field, but the Web API doesn't like it for some reason (probably because it isn't seeing it as a string but a json object perhaps)
If someone could help I would be most grateful.
Ok after messing about with this for a long time, I came up with this 'solution'.
So as #Niladri pointed out the "'" before JSON.stringify(j) was a factor but was not the only thing that needed to be changed. The main problem was actually in the controller itself.
I had this previously in my controller:
public async Task<string> UpdateProfileSettings(int id,[FromBody] string obj)
{
HttpClient clientRoute = new HttpClient();
var response = await clientRoute.PutAsync("https://something.com/api/UserSettings/put/" + id, new StringContent(obj, Encoding.UTF8, "application/json"));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
But I had to change it to:
public async Task<string> UpdateProfileSettings(int id,[FromBody] object obj)
{
HttpClient clientRoute = new HttpClient();
var response = await clientRoute.PutAsync("https://something.com/api/UserSettings/put/" + id, new StringContent(obj.ToString(), Encoding.UTF8, "application/json"));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
Notice the change of [FromBody] string obj to [FromBody] object obj and also
changed StringContent(obj, Encoding.UTF8, "application/json")) to StringContent(obj.ToString(), Encoding.UTF8, "application/json"))
My previous method with "'" before JSON.stringify(j) works if your controller [FromBody] is of string type and you aren't looking to pump a string which looks like JSON into your controller.
I apologise if this is a bad explanation but tried my best and it worked for me
This is very similar to mcc20's own fix, but I didn't get that code to work. The 2.1 framework has Issues https://github.com/aspnet/Mvc/issues/7609 and https://github.com/aspnet/Mvc/issues/7799. I got this JSON post to complex class working in 2.1: client javascript is unchanged:
var payload = JSON.stringify({ "name": document.getElementById('firstname').value, "email": document.getElementById('email').value, "captcha": grecaptcha.getResponse() });
var oReq = new XMLHttpRequest();
oReq.ContentType = "application/json";
oReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("update").innerHTML = this.responseText;
}
else document.getElementById("update").innerHTML = "not 4&200! : " + this.responseText;
};
oReq.open('POST', 'api/u');
oReq.send(payload);
and the controller has:
[Route("api/[controller]")]
// [ApiController] // works either way
public class UController : ControllerBase
{
[HttpPost]
public async Task<string> signUp()
{
String body;
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
body = await reader.ReadToEndAsync();
}
UserSignup user = JsonConvert.DeserializeObject<UserSignup>(body);
return user.email;
}
}
I was trying something like ([FromBody] UserSignup user) getting Mvc.SerializableError and "The input was not valid." Soon to be on https://github.com/Hover-Us/
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.
is there a javascript where I can populate a gridview from the database? For example is there a javascript for this code?
gvRFPCorpCode is the name of my gridview
private void fillCorpCode()
{
DataSet ds = new DataSet();
data.gRowId = this.txtROWID.Text;
ds = data.GetCorpCode();
if (ds != null)
{
if (ds.Tables[0].Rows.Count > 0)
{
this.gvRFPCorpCode.DataSource = ds.Tables[0];
this.gvRFPCorpCode.DataBind();
}
}
}
ds = data.GetCorpCode(); is equal to this:
public DataSet GetCorpCode()
{
DataSet ds = new DataSet();
SqlParameter[] sqlParam = new SqlParameter[]
{
new SqlParameter("#RowId",sRowId)
};
if (this.InitDataLayerObject() == true)
{
ds = this.ExecuteQuery("dbo.sp_ESS_RFP_GetCorpCode", sqlParam);
}
return ds;
}
It's a stored procedure, here is my stored procedure "dbo.sp_ESS_RFP_GetCorpCode"
ALTER PROCEDURE [dbo].[sp_ESS_RFP_GetCorpCode]
-- Add the parameters for the stored procedure here
#RowId varchar(max)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare #xml as xml
select
#xml =convert(xml,CORPCODE)
from Tbl_ESS_Request_For_Payment_Save
where ROWID=#RowId
select
tbl.col.value('CorpCode[1]', 'varchar(100)') as CorpCode,
tbl.col.value('Amount[1]', 'varchar(100)')as Amount
from #xml.nodes('/NewDataSet/Table1') tbl(col)
END
What I want is to have a javascript equivalent to private void fillCorpCode to populate it on my gridview, BTW, You might ask why I need a javascript if i already have a code in c#, It's because of some process in my program and it is difficult to explain. So please help me on this one, thank you in advance!
do like this
function getJSONData(selVal, callbackName) {
selVal = encodeURI(selVal);
var formdata = { };// any data you want to pass as input
$.ajax({
type: "POST",
url: "aspx",
data: formdata,
cache: false,
success: function (data) {
callbackName(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error in processing data !!' + thrownError);
},
async: false
});
}
function createTable() {
mytable = $('<table Class="table table-striped table-bordered table-hover"></table>').attr({ id: "basicTable" });
// alert(rowData);
var rowobj = JSON.parse(rowData);
// To populate header
var firstrow;
var firstrow = $('<tr></tr>').appendTo(mytable);
$('<td></td>').text('Entity Name').appendTo(firstrow);
$('<td></td>').text('Attribute Name').appendTo(firstrow);
$('<td></td>').text(' Value').appendTo(firstrow);
// To populate rows
$.each(rowobj, function (i, obj) {
$('<td valign="middle"></td>').text(obj.ParentName).appendTo(row);
$('<td valign="middle"></td>').text(obj.ParentName1).appendTo(row);
$('<td valign="middle"></td>').text(obj.ParentName2).appendTo(row);});
}
//C# method
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static string Mymethod(string entityName, string entityType, string filterValues)
{
List<MasterFields> fields = null;
ServiceWrapper<ILOSService>.Perform(svcClient =>
{
fields = getfields();
});
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(fields);
return output;
}
I have a field for a ZIP Code.
I want that, when the person fills this field with a zip code and click in another field, triggers a event (onBlur).
This Event will execute a select in database and get the address and fill the other fields with this information.
I read that is not a good idea execute a Controller Method from the View.
So, how can I develop this?
My zip code field:
<div class="editor-field">
#Html.Label("ZIP CODE")
#Html.Editor("zipCodeClient")
</div>
Thanks!
If you have access to jQuery I would use it's ajax function to call a wcf web service that returns the relevant address information in a JSON format. Otherwise, you could create your own XHR request and parse the response.
$('#zipCodeClient').blur(function() {
var zipCode = $(this).val();
if(zipCode.length >= 5 && zipCode.length <= 10) {
$.ajax({
type: 'GET',
data: { ZipCode: zipCode },
url: 'something/ZipCodeToAddressService',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
var responseObject = jQuery.parseJSON(data);
$('#cityTextBox').val(responseObject.City);
$('#stateTextBox').val(responseObject.State);
}
});
}
else {
// zip code not valid
}
});
In WCF:
[ServiceContract()]
public interface IAddressServices
{
[OperationContract()]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string ZipCodeToAddressService(string ZipCode);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class AddressServices : IAddressServices
{
public string ZipCodeToAddressService(string ZipCode)
{
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
using (SqlCommand sqlCmd = new SqlCommand("ZipCodeToAddressStoredProc", sqlConnection))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("#Zip", SqlDbType.NVarChar).Value = ZipCode;
sqlConnection.Open();
SqlDataReader sDR = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable tbl = new DataTable();
tbl.Load(sDR);
sDR.Close();
var citystateData = from DataRow Row in tbl.AsEnumerable()
select new
{
City = Row.Field<string>("City"),
State = Row.Field<string>("State")
};
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
js.Serialize(cityStateData, sb);
string rtrnCityStateData = sb.ToString();
return rtrnCityStateData;
}
}
}
}