public class theatresController : ApiController
{
[HttpGet]
public static DataTable GetAlltheatredet()
{
try
{
string connString = "Server=localhost;database=mytable;uid=root;";
string query = "SELECT TheatreName FROM `mytable`.`theatredetails`";
MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
DataSet DS = new DataSet();
ma.Fill(DS);
return DS.Tables[0];
}
catch (MySqlException e)
{
throw new Exception(e.Message);
}
}
I am fetching my table data from DB by using datatable. How can I convert all these datas to json
I tried by using this in an html file
$(document).ready(function ()
{
$("#Theaterdet").click(function ()
{
alert("in document submit");
$.ajax({
type: "GET",
url: "/api/theatres/",
dataType: 'json',
success: function (data)
{
},
error: function ()
{
alert("Error while invoking the Web API");
}
});
});
});
But I got error... How can I implement this functionality?
Related
I tried to binding remote DataSource for my Kendo DropDownList, but the Kendo Datasource could parse the json response correctly. The result turns out to be "undefined" and recognize every single charachter in the data as a selection. I have no idea where the bug is, please help me!
Responce from controllor:
"[{"CODE_ID":"A","CODE_NAME":"Free"},{"CODE_ID":"B","CODE_NAME":"Borrowed"},{"CODE_ID":"U","CODE_NAME":"Unable"},{"CODE_ID":"C","CODE_NAME":"To be Borrowed"}]"
HTML Result
Front-end js code for Kendo DropDownList
$(document).ready(function () {
$("#search_category").kendoDropDownList({
dataTextField: "CODE_NAME",
dataValueField: "CODE_ID",
dataSource: {
transport: {
read: {
type: "GET",
url: "/BookData/GetDataList",
data: { name: "category" },
dataType: "json"
}
},
},
});
}
BookDataControllor
[HttpGet()]
public JsonResult GetDatalist(string name)
{
string result;
try
{
switch (name)
{
case "category":
result = codeService.GetDataList("CODE_ID, CODE_NAME",
"BOOK_CODE", "CODE_TYPE = 'BOOK_STATUS'");
break;
default:
return Json(false);
}
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(false);
}
}
back-end class CodeService
private DataTable GetDataTable(string sql)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(this.GetDBConnectionString()))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd);
sqlAdapter.Fill(dt);
conn.Close();
}
return dt;
}
public string GetDataList(string col, string src, string cond)
{
DataTable dt = GetDataTable(string.Format(#"SELECT {0} FROM {1} WHERE {2}",
col, src, cond).ToUpper());
string result = JsonConvert.SerializeObject(dt);
return result;
}
You are returning CODE_ID and CODE_NAME in your controller, but the values you're referencing on the front-end are Category_Name and Category_ID. Change them to reference the correct column names:
$('#search_category').kendoDropDownList({
dataTextField: 'CODE_NAME',
dataValueField: 'CODE_ID',
dataSource: {
transport: {
read: {
type: 'GET',
url: '/BookData/GetDataList',
data: { name: 'category' },
dataType: 'json',
success: function (response) {
console.log(response);
}
}
}
}
});
It seems that even returning your data with Json(result) as JsonResult, the response content could be a string, which the DataSource is not handling the right way.
Try enrusing that it will be json with parse method:
$(document).ready(function () {
$("#search_category").kendoDropDownList({
dataTextField: "CODE_NAME",
dataValueField: "CODE_ID",
dataSource: {
transport: {
read: {
type: "GET",
url: "/BookData/GetDataList",
data: { name: "category" },
dataType: "json"
}
},
schema: {
parse: function(data) {
// Here you can check what 'data' really is
console.log(data);
return JSON.parse(data);
}
}
},
});
}
I have web page with dropdown list "ListBox" with email address of users.
How do I make a function that update the dropdownlist "ListBox" everytime when I add new email user in the dropdown list ?
I have trying this solution without success because the dropdown list it emptied, instead of add new user.
This is my code :
nnewuser.txuser = $("[id*=txuser]").val();
$.ajax({
type: "POST",
url: "prefix.aspx/Savepnusers" + qString,
data: '{nnewuser: ' + JSON.stringify(nnewuser) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if ($("[id*=txuser]").val()) {
alert("Ok");
alert(JSON.stringify(nnewuser));
$("[id*=ListBox1]").html(response);
}
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error : " + thrownError + JSON.stringify(nnewuser));
}
});
return false;
});
Savepnusers
public class pnnusers
{
public string txuser { get; set; }
}
[WebMethod(EnableSession = true)]
[ScriptMethod]
public static void Savepnusers(pnnusers nnewuser)
{
string sql = #String.Format(" INSERT INTO `tbl_email` (email) VALUES (?); ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, cn))
{
try
{
command.Connection.Open();
command.Parameters.AddWithValue("param1", nnewuser.txuser.ToString());
command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Connection.Close();
}
}
}
}
DropDownList
private void MTListBox1()
{
DataTable dt = new DataTable();
sql = #String.Format(" SELECT ");
sql += String.Format(" LOWER(Email) AS UserEmail ");
sql += String.Format(" FROM ");
sql += String.Format(" tbl_email ORDER BY LOWER(Email) ASC; ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, cn))
{
try
{
command.Connection.Open();
OdbcDataAdapter sqlDa = new OdbcDataAdapter(command);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
ListBox1.DataTextField = "UserEmail";
ListBox1.DataValueField = "UserEmail";
ListBox1.DataSource = dt;
ListBox1.DataBind();
}
}
catch (OdbcException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
command.Connection.Close();
}
}
}
}
There are 2 main problems here:
First, your Savepnusers method does not return anything, so you can't use response in AJAX calls. What you need is that re-initialize ListBox1 or append new item after Savepnusers complete successfully:
Secondly, it seems you can't send nnewuser as parameter correctly. You don't need to have pnnusers class instead just use string type as a parameter.
So server-side:
public static void Savepnusers(string nnewuser)
On client-side, you need to add dropdownlist item with jquery:
var txtUser = $("[id*=txuser]").val();
$.ajax({
type: "POST",
url: "prefix.aspx/Savepnusers",
data: JSON.stringify({ nnewuser: txtUser }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
//Since you can't use response object, you can append new item to dropdownlist
if (txtUser) {
$("[id*=ListBox1]").append('<option value="'+txtUser+'">'+txtUser+'</option>');
}
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error : " + thrownError + JSON.stringify(nnewuser));
}
});
See: asp dropdownlist dynamic value from javascript issue
I have a problem displaying the data in the dropdown list using select2. I think the reason is the Query returning many rows. when I limit the number of Row to 50 (where Rownum <=100 ) the data displayed but when I remove the where condition no data display. The PatientDemo table has more than 600000 rows Any help how to solve this issue. I am using Orcale and C#
View
<link href="~/Content/css/select2.min.css" rel="stylesheet" />
<div class="jumbotron">
<input type="hidden" id="textBoxVal" />
<select class="mySelect2" style="width:500px;">
</select>
</div>
<script>
$(document).ready(function () {
$(".mySelect2").select2({
placeholder: "Select category",
allowClear: true,
theme: "classic",
ajax: {
url: "/Home/GetCategory",
dataType: 'json',
delay: 10000,
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (data, params) {
return {
results: data
};
}
}
});
});
$(".mySelect2").on("change", function () {
var catId = $(this).val();
$("#textBoxVal").val(catId);
var textBoxValueData = $("#textBoxVal").val();
$.ajax({
url: '/Home/Save?data=' + textBoxValueData,
dataType: 'json',
type: 'post',
});
});
Model
public class Select2Model
{
public string id { get; set; }
public string text { get; set; }
}
C#
public JsonResult GetCategory(string searchTerm)
{
var list = new List<Select2Model>();
using (OracleConnection conn = new OracleConnection(WebConfigurationManager.ConnectionStrings["PatientRecord"].ConnectionString))
{
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = #"SELECT PATIENT, NAMEFORWARD FROM PATIENTDEMO ";
cmd.CommandType = CommandType.Text;
OracleDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
list.Add(new Select2Model()
{
text = rdr["NAMEFORWARD"].ToString(),
id = rdr["Patient"].ToString()
});
}
var dataList = list.ToList();
if (searchTerm != null)
{
dataList = list.Where(x => x.text.Contains(searchTerm)).ToList();
}
var modifiedData = dataList.Select(x => new {
id = x.id,
text = x.text
});
return Json(modifiedData, JsonRequestBehavior.AllowGet);
}
}
public JsonResult Save(string data)
{
return Json(0, JsonRequestBehavior.AllowGet);
}
600000 rows in a drop down list is not a user friendly one. Instead why don't you implement a drop down list with auto complete?
Check the example at the bottom of this page: https://api.jqueryui.com/autocomplete/
Update:
In your case you source would be a ajax call to the server side to pull the relevant data. Like this:
$('#myautocomplete').autocomplete({
type: "POST",
minLength: 3,
source : function (request, response)
{
var source_url = "../handlers/MyLookup.ashx?someparameter=" + $("#someparameter").val();
$.ajax({
url: source_url,
dataType: "json",
data: request,
success: function (data) { response(data); },
error : function (a,b,c) { HandleLookUpError(a); }
});
},
select: function (event, ui) { $('#result').val(ui.item.id); }
});
Note the source_url variable and the ajax call in the above code.
More details on how to load data from server side is here: https://stackoverflow.com/a/8873641/218408
I need to return DataTable to Ajax from c#(WebMethod).
I'm sending 'Value" to WebMethod. Value is received and used as a parameter for a procedure in the code below(getObj.getValuesTableAdapter(Value);).
Then procedure returns datatable(dtObj) and ajax should receive it back in the "success" part.
I need help with these code. I tried everything but failed.
I can't return DataTable directly from [WebMethod] like this. I need to convert DataTable to JSON before sending to client somehow.
This is my c# code:
[WebMethod(EnableSession = true)]
public static DataTable GetObject(int Value)
{
LogicTableAdapters.getValuesTableAdapter getObj = new LogicTableAdapters.getValuesTableAdapter();
DataTable getObj = getObj.getValuesTableAdapter(Value);
DataTable dtObj = new DataTable();
dtObj.Columns.AddRange(new DataColumn[4]{
new DataColumn("ObjectID", typeof(string)),
new DataColumn("ObjectName", typeof(string)),
new DataColumn("ObjectValue", typeof(string)),
new DataColumn("ParentID", typeof(int)),
});
foreach (DataRow dr in getObj.Rows)
{
dtCh.Rows.Add(dr["ObjectID"].ToString(), dr["ObjectName"] == DBNull.Value ? null : dr["ObjectValue"].ToString(), dr["ParentID"].ToString());
}
return dtObj;
}
This is my ajax:
$(document).on('click', ".Btn", function () {
header = $(this).closest('tr').find('.ColumnID').text()
console.log(Value);
$.ajax({
type: "POST",
url: "MyAdmin.aspx/GetObject",
data: JSON.stringify({ 'Value': Value }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
//code that should receive datatable to be displayed
},
error: function () {
}
});
});
Thanks in advance !
try following
create a class for sending data to frontend
public class DataForClientSide
{
public string id { get; set; }
public string name { get; set; }
public string value{ get; set; }
}
Edit Your webmethod as follow
[WebMethod(EnableSession = true)]
public static DataForClientSide[] GetObject(int Value)
{
List<DataForClientSide> details = new List<DataForClientSide>();
LogicTableAdapters.getValuesTableAdapter getObj = new LogicTableAdapters.getValuesTableAdapter();
DataTable getObj = getObj.getValuesTableAdapter(Value);
DataTable dtObj = new DataTable();
dtObj.Columns.AddRange(new DataColumn[4]{ new DataColumn("ObjectID", typeof(string)), new DataColumn("ObjectName", typeof(string)), new DataColumn("ObjectValue", typeof(string)), new DataColumn("ParentID", typeof(int)),
});
foreach (DataRow dr in getObj.Rows)
{
DataForClientSide Info= new DataForClientSide();
Info.id = dr["ObjectID"].ToString();
Info.name = dr["ObjectName"].ToString();
Info.value = dr["ObjectValue"].ToString();
//multiple data as u want. . . . .
details.Add(Info);
}
return details.ToArray();
}
Write following code in your ajax function to get values
success: function (data) {
if(data.d.length>0)
{
$.each(data,function(i,values){
//you can get all values as per each iteration as follow
//to get id
values.id;
//to get name
values.name;
//to get value
values.value;
});
}
}
I get data from Webmethod & it need to bind to a table.But my Jquery function not success.Not call webmethod because of Ajax call error.
My Webmethod is
[WebMethod, ScriptMethod]
public static List<UploadedFiles> GetAllUploadedFiles()
{
List<UploadedFiles> UploadedFilesDetails = new List<UploadedFiles>();
try
{
SqlCommand comGetAllFiles = new SqlCommand("SP_GetAllUploadedFiles", conDB);
comGetAllFiles.CommandType = CommandType.StoredProcedure;
if (conDB.State == ConnectionState.Closed)
conDB.Open();
SqlDataReader rdr = comGetAllFiles.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
{
UploadedFilesDetails.Add(new UploadedFiles
{
Id = (int)r["Id"],
UserId =(Guid)r["UserId"],
FilePath = r["FilePath"].ToString(),
Date =(DateTime) r["Date"]
});
}
}
catch(Exception ee)
{
}
finally
{
conDB.Close();
}
return UploadedFilesDetails;
My Ajax Function
<script>
$(function () {
LoadUploadFiles();
});
function LoadUploadFiles() {
var url = '<%=ResolveUrl("WebMethods.aspx/GetAllUploadedFiles") %>';
$.ajax({
url: url,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (Result) {
alert("x");//<-- This alert firing
$.each(Result.d, function (key, value) {
alert(Result.d); //<-- Thisone not firing
$("#uploaddata").append($("<table><tr></tr></table>").val
(value.Id).html(value.FilePath));
});
},
error: function (e, x) {
alert(x.ResponseText);
}
});
}
</script>