Call Webmethod to Fill DropDownList - javascript

I want to fill the DropDownList via SqlQuery in webmethod. But it gives internal Server error.
Except for the error, can't I just do this in javascript?
function doldur() {
$.ajax({
url: "UserServis.asmx/ListDoldur",
type: "post",
dataType: "json",
contentType: "application/json;charset=utf-8",
data: "{ 'sysName': 'Sudio', 'categoryID': " + 544 + " }",
success: function (data) {
var result = data.d;
alert(result);
},
error: function (requeset, status, error) {
alert(error);
}
});
}
[WebMethod(EnableSession = true)]
public static List<string> ListDoldur()
{
List<string> retList = new List<string>();
SqlConnection baglanti = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnLEO"].ConnectionString);
SqlCommand komut = new SqlCommand("select BolumAdi from emre_bolumler ", baglanti);
SqlDataAdapter da;
DataSet ds;
DataTable dt;
baglanti.Open();
da = new SqlDataAdapter(komut);
ds = new DataSet();
da.Fill(ds,"TestTable");
dt = ds.Tables["TestTable"];
for (int i = 0; i < dt.Rows.Count; i++)
{
retList.Add(dt.Rows[i].ItemArray[0].ToString());
}
return retList;
}

Yes you can.
you are sending data to the code behind method but it does not have a parameter to accept data;
I think the simplest way is to serialize your datatable and return a JSON string, not a List<string> (maybe you can do return retList.ToArray() ? not sure);
skip the dataset, just use a table. I'm not entirely sure what's going on with the loop, but I think when you serialize the data you won't have to do that (unless you have a ton of columns to avoid).
using Newtonsoft.Json;
// convert datatable to a string.
string result = JsonConvert.SerializeObject(tbl);
when the data is returned to the ajax method, create the dropdown options.

Related

Need Help Diagnosing This Ajax Request Call

Need Help Diagnosing This Ajax Request Call.
filtered text is a text box from an input box further up the page , with filters is a Boolean checking if the user wants to search for anything at all and filtered text is what the user would like to filter by.
function GetData(torf) {
var watever = { "withfilters": torf, "filteredtext": $('#SortOrdersBy2').val() };
$.ajax({
url: '/WebService.asmx/GetData',
method: 'post',
dataType: 'json',
data: JSON.stringify(watever),
contentType: "application/json; charset=utf-8",
success: function (data) {
var employeeTable = $('#datatable tbody');
var employees = data;
for (i = 0; i < employees.length; i++) {
employeeTable.append('<tr><td>' + employees[i].CustomerId + '</td><td>' + employees[i].CustomerName + '</td><td>' + employees[i].Engineer + '</td></tr>');
}
},
error: function (err) {
alert("ERROR");
}
});
}
It Goes to this web service code and runs through it on load but still displays the error function.
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string GetData(bool withfilters, string filteredtext)
{
string connectionString = ConfigurationManager.ConnectionStrings["CustomerDataConnectionString"].ConnectionString;
List<Data1> Data = new List<Data1>();
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand query = new SqlCommand
(withfilters ? "SELECT * FROM MainTable CustomerId LIKE '%" + (filteredtext) + "%' OR CustomerName LIKE '%" + (filteredtext) + "%' OR Engineer LIKE '%" + (filteredtext) + "%')"
: "SELECT * FROM MainTable",con);
SqlDataReader rdr = query.ExecuteReader();
while (rdr.Read())
{
Data1 data = new Data1();
data.CustomerId = Convert.ToInt32(rdr["CustomerId"]);
data.CustomerName = rdr["CustomerName"].ToString();
data.Engineer = rdr["Engineer"].ToString();
Data.Add(data);
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(Data);
}
Any Help Would be greatly Appreciated, need more info let me know.
In your webservice you have set the UseHttpGet=true which means that this method can be executed using Http GET request not POST
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string GetData(bool withfilters, string filteredtext)
However, in javascript you are trying to execute the method using POST from client-side
$.ajax({
url: '/WebService.asmx/GetData',
method: 'post',
dataType: 'json',
SOLUTION:
Remove the HttpGet=true from ScriptMethod attribute:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetData(bool withfilters, string filteredtext)

'undefined' reported when bind gridview using AJAX in C#

I want to bind the gridview using AJAX. So, for that I done client side code using AJAX and server side code as a webmethod.
Everything is working fine even I alert the data in success method at that time also data is showing but in loop I really confused that it is showing undefined in alert. So for that's why grid is not binding.
Here is my code
$.ajax({
type: "POST",
url: "schoolregistration.aspx/GetGridData",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#grid_schooldata").append("<tr><td>" + data.d[i].schoolName);
}
},
failure: function () {
alert("error! try again...");
}
});
using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand("select schoolname as [School Name] from tbl_schoolregistration", con))
{
con.Open();
object val = cmd.ExecuteScalar();
return val == DBNull.Value ? "" : (string)val;
}
First of all
ExecuteScalar Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
In this case you will have a single string.
Secondly beware of the name in your query leave it as schoolname not [School Name].
Then you have to Serialize into json and again parse into json in order to loop through objects.
Here is fully working code:
$.ajax({
type: "POST",
url: "schoolregistration.aspx/GetGridData",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
data = JSON.parse(data.d);
for (var i = 0; i < data.length; i++) {
$("#grid_schooldata").append("<tr><td>" + data[i].schoolname +"</td></tr>");
}
},
failure: function () {
alert("error! try again...");
}
});
[WebMethod]
public static string GetGridData()
{
using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand("select schoolname from tbl_schoolregistration", con))
{
con.Open();
//object val = cmd.ExecuteScalar();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt); // fills data from select query
// return val == DBNull.Value ? "" : (string)val;
return JsonConvert.SerializeObject(dt);
}
}

Jquery Ajax function always returns null

I have a Jquery ajax function which makes call to a c# method. The function always returns null even when the string its supposed to return is in Json format. How do I get the return value in the Jquery function?
function GetScores() {
$.ajax({
type: 'POST',
url: 'Default.aspx/GetTopScores',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
alert(data.d); // Always NULL
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('ERROR!!');
}
});
}
public static string GetTopScores()
{
string result = string.Empty;
DataTable dt = new DataTable();
try
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data Source=*****;Initial Catalog=beachlings;Persist Security Info=True;User ID=******;Password=******;MultipleActiveResultSets=True;Application Name=EntityFramework";
conn.Open();
string query = "Select TOP 20 PlayerName, SiteName, Score from HighScores ORDER BY SCORE DESC";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
string s = JsonConvert.SerializeObject(rows);
return s;
}
}
catch (Exception ex)
{
return null;
}
}
Finally found what was causing the javascript to return null. I was calling GetTopScores() from within another method and instead of returning string I was returning void. Thanks for your help :)

Why occur Internal server error in my ajax query?

I want to pass some value to server and it has to return one string.
Jquery version
<script src="js/jquery-3.1.1.js"></script>
Here is my code:
$('#btnSaveFile').click(function () {
var fileName = $('#txtFileName').val();
alert(fileName);
$.ajax({
url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
method: 'GET', //method or type ?
contentType: 'application/json',
data: '{fileName:' + fileName +'}', //UPDATED Line
dataType: 'json',
success: function (data) {
alert('success');
alert(data.d.exist);
},
error: function (error) {
alert('fail');
alert(error);
}
});
});
Aspx code
[WebMethod]
public static string getFileExistOrNot(string fileName)
{
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select ReportData FROM [HQWebMatajer].[dbo].[ReportSave] where Userfilename=#UserFileName and ReportName=#ReportName";
cmd.Parameters.AddWithValue("#UserFileName", fileName);
cmd.Parameters.AddWithValue("#ReportName", "TotalSales");
con.Open();
var data = cmd.ExecuteScalar();
if (data != null)
{
string exist = "dataExist";
return exist;
}
else
{
string exist = "notExist";
return exist;
}
}
}
Error Msg
GET http://localhost:55047/ReportTotalSalesPivot.aspx/getFileExistOrNot?fileName:www} 500 (Internal Server Error)
ExceptionType:"System.InvalidOperationException"
Message:"An attempt was made to call the method 'getFileExistOrNot' using a GET request, which is not allowed."
StackTrace:" at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
↵ at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)".
I think this error it occurs in server side. But I don't know what is that
Updated
Error Message:"Invalid web service call, missing value for parameter:'fileName'."
Send your data like below:
In object format
data: { fileName:fileName },
OR
As a String
data = "fileName="+filename;
After one day I found What was my mistake.
This is the answer
data:'{fileName:"'+fileName+'"}'

Retrieve binary data from C# with Ajax

I'm a bit new in web development and I can't achieve what I'm trying to do.
I have a Database with a table called "PI_Banners", where I store some images. This table stores an ID and a VARBINARY column that contains the binary data of the image.
What I'm trying to do, is to retrieve that data with an Ajax request to a C# function, and create a "img" tag using Data URI Scheme. Then append that new image to a div
This is what I got:
Ajax call:
$(document).ready(function() {
var dto = {};
var dtoJSON = JSON.stringify(dto);
$.ajax({
async: false,
url: 'BannerRotativo.aspx/devuelveBanners',
cache: false,
dataType: 'json',
type: "POST",
data: dtoJSON,
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, jqXHR) {
responsedevuelveBanners(data);
},
error: errorResponse
});
});
Being "devuelveBanners" the C# function.
C# code:
public static string devuelveBanners()
{
DataReader DR;
DR = listaBanners();
//armaJson creates the Json string from the DataReader.
string strJson = GENERAL.armaJson(DR);
return strJson;
}
public DataReader listaBanners()
{
try
{
string strComando;
sqlCommand SQLC;
DataReader DR;
strComando = "SELECT banner_img FROM PI_Banners";
//sqlCon is the connection, and is open already.
SQLC = new System.Data.SqlClient.SqlCommand(strComando, sqlCon);
SQLC.CommandType = CommandType.Text;
DR = SQLC.ExecuteReader();
return DR;
}
catch (Exception ex)
{
throw ex;
}
}
When I parse the Json string back, and create the image:
function responsedevuelveBanners(data)
{
var datos = JSON.parse(data.d);
$("#imgContainer").append("<img src='data:image/jpg;base64," + datos.Rows[0].Row[0].banner_img + "' />");
}
the image is created but doesn't show up, because it has this URL:
data:image/jpg;base64,System.Byte[]
I know I'm doing something terribly wrong trying to retrieve the json data this way, but I don't know how to achieve this!
Thanks in advance!
In order to use <img src="data:image/PNG;base64' the base64 part is because you need to return a Base64 string instead of array of bytes therefore you need to convert your byte[] to 64Base using: Convert.ToBase64String(buffer)
So using your code as example:
ImageConverter imageConverter = new ImageConverter();
byte[] resourceByteArray = (byte[])imageConverter.ConvertTo(_YourObj.GetImage(), typeof(byte[]));
Your WebApi method should be returning:
return Convert.ToBase64String(resourceByteArray);

Categories