I'm trying to create a Monthly report in MVC. For that I need to create the days of user selected month as it's heading. But When I try to set it by sing the jquery It show some errors.
Cannot use 'in' operator to search for '61764' in [{"Name":"Abel John","Father Name":John,"Sex":"Male","Date of Birth ....
I'm new to Jquery and MVC . here Is my code . Please help me to solve the issue.
$.ajax({
type: "POST",
url: '#Url.Action("GetLeaveDeatais", "LeaveDetails")?year=' + date,
contentType: "application/json; charset=utf-8",
year: { year: '2013' },
contentType: 'application/html; charset=utf-8',
success: function () {
}
})
.success(function (result) {
$('#divDetails').html(function () {
var cols = [];
var dataSet = result;
var my_columns = [];
$.each(JSON.parse(JSON.stringify(dataSet)), function (key, value) {
var my_item = {};
my_item.data = key;
my_item.title = key;
my_columns.push(my_item);
});
var table = $('#example').DataTable({
columns: my_columns
});
}
);
});
My Controler
public string GetLeaveDeatais(string year)
{
List<DataRow> list = new List<DataRow>();
DataTable dt = new DataTable();
MusterRoll mstRoll= new MusterRoll();
dt = clsBD.GetEmpLeaveDeatils("2019-05-1");
if (dt != null)
list=dt.AsEnumerable().ToList();
JavaScriptSerializer js = new JavaScriptSerializer();
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
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);
}
return serializer.Serialize(rows);
}
Please find me to get a solution soon.
Thanks in Advance
Related
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;
});
}
}
Hello Friends I am getting not error but some issue in getting date in ajax success so tell me how can i correct this
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: {},
url: "edit-registration.aspx/GetUserInfo",
datatype: 'json',
success: function (data) {
var objData = eval("(" + data.d + ")");
var rows = objData.Table1.length - 1;
$("#disabilityCertIssueDate").val(objData.Table1[0][15]);
},
error: function (e, v) {
alert('there is some error');
}
});
Data are return in json from abc.aspx.cs page
public static string DataSetToJSON(DataSet ds)
{
try
{
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (DataTable dt in ds.Tables)
{
object[] arr = new object[dt.Rows.Count + 1];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
arr[i] = dt.Rows[i].ItemArray;
}
dict.Add(dt.TableName, arr);
}
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Serialize(dict);
}
catch (Exception e)
{
return e.Message;
}
}
I am getting correct date format on cs page but in success i am getting /Date(787170600000)/ this so how can i retrieve in correct format and set to html5 date control
Format date before passing to JS as string - It would be valid value for html5 input.
Example:
DateTime.Now.ToString("yyyy-dd-MM");
javascript date specification
I have a problem with converting datasource to json_data. Here is my code:
In my default.aspx.cs:
[WebMethod]
public string GetJson()
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
DataTable dtEmployee = new DataTable();
dtEmployee.Columns.Add("EmpId", typeof(int));
dtEmployee.Columns.Add("Name", typeof(string));
dtEmployee.Columns.Add("Address", typeof(string));
dtEmployee.Columns.Add("Date", typeof(DateTime));
//
// Here we add five DataRows.
//
dtEmployee.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
dtEmployee.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
dtEmployee.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);
foreach (DataRow dr in dtEmployee.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dtEmployee.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
And here is in my default.apsx page:
var data2 = { };
function GetJsonData(callback) {
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/GetJson",
//contentType: "application/json; charset=utf-8",
//data: '{name:""}',
dataType: "json",
cache: false,
success: function(msg) {
callback(msg);
},
error: function(err) {
alert('error');
}
});
}
data2 = GetJsonData();
$(function() {
$("#MainTree,#SubTree").jstree({
"json_data": {
"data": data2,
},
"plugins": ["themes", "json_data", "ui", "dnd"]
});
});
When I hide "data", ofcourse it won't create node. But now I want to call method GetJson from default.aspx.cs to get json_data from datasource. It always show "..Loading".. I'm using jsTree and just .net framework 2.0..Please help me to find out the solution for this..Thanks
Use Default.aspx/GetJson instead of Default.aspx.cs/GetJson.
In addition to changing the filename(as #Alex Filipovici mentioned), your method needs to be static.
[WebMethod]
public static string GetJson()
{
}
EDIT:::
This is what I did and got results back:
$(document).ready(function () {
$("[id$=_btnPostReminder]").click(function () {
var a = "";
var remindertext = "";
var re = "";
var res = "";
$.ajax({
type: "POST",
url: "Default.aspx/GetJson",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function Ret(response) {
var Result = response.d
alert(Result)
return false;
},
error: function (data, status, jqXHR) {
alert(jqXHR);
}
});
return false;
});
});
here is my code:
var data = "";
$(function() {
$("#MainTree,#SubTree").jstree({
"json_data": {
"data": data,
"ajax":{
type: "POST",
async: true,
url: "Default.aspx/GetJson",
contentType: "application/json; charset=utf-8",
//data: '{name:""}',
dataType: "json",
cache: false,
success: function(msg) {
data = msg;
},
error: function(err) {
alert(err);
}
},
},
"plugins": ["themes", "json_data", "ui", "dnd"]
});
});
This is my GetJson method:
[System.Web.Services.WebMethod]
public static string GetJson()
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
DataTable dtEmployee = new DataTable();
dtEmployee.Columns.Add("EmpId", typeof(int));
dtEmployee.Columns.Add("Name", typeof(string));
dtEmployee.Columns.Add("Address", typeof(string));
dtEmployee.Columns.Add("Date", typeof(DateTime));
//
// Here we add five DataRows.
//
dtEmployee.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
dtEmployee.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
dtEmployee.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);
foreach (DataRow dr in dtEmployee.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dtEmployee.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
In my Default.aspx.cs, I created a method name GetJson, when I run this code, it returned alert(error). Please help me to find out what was happened?
Editted: when i check in browser,the method get status code 200 OK, but in respone..it show me the page Default.aspx(context html)
I am trying to get a selected item from asp.net dropdownlist control which is populated from jquery ajax call. I am able to loop through the items on the screen, see the options attached in the source of the page but when I am trying to get the value from the c# backend code I am getting blank value.
This is what I have:
$('#<%=Button2.ClientID %>').click(function () {
var Dropdown2 = $('#<%=ddlListAgents.ClientID %>');
Dropdown2.empty();
$.ajax({
type: "POST",
url: "WebForm3.aspx/fetchData",
data: "{selectedAgent: '" + $('#<%=txtAgentNameText.ClientID %>').val() +"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
Dropdown2.append(new Option("--Select Agent --", 0));
$.each(response.d, function (index, item) {
Dropdown2.append(new Option(item.Name, item.ID));
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
Everything is set ok after that call and I am able to browse the options. But when I am clicking a button and trying to get the selected value in this code (test code):
protected void btnSelectAgentAdd_ServerClick(object sender, EventArgs e)
{
foreach (ListItem item in ddlListAgents.Items)
{
if (item.Selected.Equals(true))
{
item.Value.ToString();
}
else
{
item.Value.ToString();
}
}
string one = ddlListAgents.SelectedValue;
}
After the first loop the code steps out from the for loop, and the ddlListAgents.SelectedValue is equal to empty string.
This is the method I am using to get the dataset:
[WebMethod]
public static List<AgentName> fetchData(string selectedAgent)
{
Dictionary<string, string> list = new Dictionary<string, string>();
BL.Client client = new BL.Client();
var agents = new List<AgentName>();
if (selectedAgent != string.Empty)
{
list = client.GetAgentNamesForPopupSearch(selectedAgent);
}
foreach (KeyValuePair<string, string> val in list)
{
agents.Add(new AgentName { ID = Convert.ToInt32(val.Key), Name = val.Value });
}
return agents;
}
Every advice is welcome.
Thanks in advance, Laziale
EDIT:
Page Load event added:
if (!IsPostBack)
{
Dictionary<string, string> list = new Dictionary<string, string>();
BL.Client client = new BL.Client();
list = client.GetAgentNamesForPolicies2(Convert.ToInt32(4));
ddlAgentName.DataSource = list;
ddlAgentName.DataTextField = "Value";
ddlAgentName.DataValueField = "Key";
ddlAgentName.DataBind();
ddlAgentName.Items.Insert(0, new ListItem("-- Select Agent --", string.Empty));
}
string selectedValue = Request.Form[ddlLanguage.UniqueID];