jQuery jTable turned off pagination is causing an issue - c#

I am using a jQuery jTable with a 'Slide In' effect, so everytime a tab is clicked, it brings the data with 'Slide In' transition. However, I recently turned off the 'Pagination' feature in jQuery jTable and since then the 'Slide In' transition gets stuck in the middle while giving out the following message "No Data Available" and once the transitions is finished then only it brings the data.
Very Strange.. it gets stuck really bad in the middle and upon transition completion it then only bring the data and is a major issue.
Is there any way that I can have a ajax loading before it brings the data? or can I use any another transitions instead of the glitchy 'Slide In'?
I am bringing the data from a local Excel file. Any help is highly appreciated :)
Slide in Transition code:
$(document).on('click', '.PlayStatisticClass', function (e) {
var $marginLefty = $("div[class='" + this.id + " win-ui-dark slide']")
if (!$marginLefty.hasClass('slide in')) {
if (this.id === "PlayStatisticone" || this.id === "PlayStatistictwo" || this.id === "PlayStatisticthree" || this.id === "PlayStatisticfour" || this.id === "PlayStatisticfive"
|| this.id === "PlayStatisticsix" || this.id === "PlayStatisticseven" || this.id === "PlayStatisticeight" || this.id === "PlayStatisticnine") {
$marginLefty.addClass('registrationFormSlideIn').css('width', "");
}
else {
}
}
else {
$marginLefty.removeClass('slide in').addClass('slide').css('width', 0);
}
});
jTable View Code: Where I turned off Pagination:
$(document).ready(function () {
$('#TopPlayedTracksContainer1').jtable({
title: 'Top Played Genres List',
paging: false,
pageSize: 1,
sorting: true,
defaultSorting: 'NoOfPlays DESC',
actions: {
listAction: '#Url.Action("BilingReportList")'
},
fields: {
TrackID: {
title: 'Track ID',
tooltip: 'Track ID'
},
TrackName: {
title: 'Track Name',
tooltip: 'Track Name',
key: true,
create: false,
edit: false,
resize: false,
},
ArtistName: {
title: 'Artist Name',
tooltip: 'Artist Name'
},
Times: {
title: 'Times',
tooltip: 'Times'
},
}
});
$('#TopPlayedTracksContainer1').jtable('load');
});
Controller Code: Getting data from a local excel file:
public JsonResult BilingReportList(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
{
try
{
if (Request.IsAuthenticated == true)
{
string Path = #"C:\\5Newwithdate.xls";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
System.Data.DataTable data = new System.Data.DataTable();
da.Fill(data);
con.Close();
List<TopPlayed> daa = new List<TopPlayed>();
foreach (DataRow p in data.Rows)
{
TopPlayed top = new TopPlayed()
{
TrackID = Convert.ToInt32(p.Field<double>("ID")),
TrackName = p.Field<string>("Track Name"),
ArtistName = p.Field<string>("Artist Name"),
Times = Convert.ToInt32(p.Field<double>("NoOfPlays"))
};
daa.Add(top);
}
var newlist = daa.OrderByDescending(i => i.Times).ToList();
return Json(new { Result = "OK", Records = newlist, TotalRecordCount = daa.Count });
}
return Json(new { Result = "ERROR" });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}

You need to delete those parameters:
int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null
public JsonResult BilingReportList()
{
try
{
if (Request.IsAuthenticated == true)
{
string Path = #"C:\\5Newwithdate.xls";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
System.Data.DataTable data = new System.Data.DataTable();
da.Fill(data);
con.Close();
List<TopPlayed> daa = new List<TopPlayed>();
foreach (DataRow p in data.Rows)
{
TopPlayed top = new TopPlayed()
{
TrackID = Convert.ToInt32(p.Field<double>("ID")),
TrackName = p.Field<string>("Track Name"),
ArtistName = p.Field<string>("Artist Name"),
Times = Convert.ToInt32(p.Field<double>("NoOfPlays"))
};
daa.Add(top);
}
var newlist = daa.OrderByDescending(i => i.Times).ToList();
return Json(new { Result = "OK", Records = newlist, TotalRecordCount = daa.Count });
}
return Json(new { Result = "ERROR" });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}

Related

Populate a textbox based on selected value from cascading dropdown using ASP.NET MVC

I tried to search posts, without any result either, maybe I didn't use the right words.
I am using ASP.NET MVC to create a webpage with a form.
The form has a two dropdownlist and a textbox.
The first dropdownlist is populated with values from the database.
The second dropdownlist is populated with values cascading, based on the selected first dropdownlist value.
The textbox will populate with a value from the same table and the second dropdownlist, based on the selected second dropdownlist value.
I have tried call a function from my controller inside of my view, without success. Don't have error but the textbox is empty.
Please, can you help me.
My code below
View
#Html.DropDownListFor(m => m.StateId, Model.States, "Select", new { #id = "StateId", #Class = "textarea" })
#Html.TextBoxFor(m => m.GPS, new { #Class = "textarea", placeholder = "GPS" })
#section Scripts {
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/DatePicker.js");
#Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(function () {
$('[id*=StateId]').on('change', function () {
var fruitId = $(this).find("option:selected").val();
if (fruitId != "") {
$.ajax({
type: "POST",
url: "/Home/GetFruitName",
data: "id=" + fruitId,
success: function (response) {
if (response != "") {
$('[id*=GPS]').val(response);
} else {
$('[id*=GPS]').val('');
}
}
});
} else {
$('[id*=GPS]').val('');
}
});
});
$(function () {
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{type: "' + id + '", value: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
PopulateDropDown("#CityId", list);
break;
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function DisableDropDown(dropDownId) {
$(dropDownId).attr("disabled", "disabled");
$(dropDownId).empty().append('<option selected="selected" value="">Select</option>');
}
function PopulateDropDown(dropDownId, list) {
if (list != null && list.length > 0) {
$(dropDownId).removeAttr("disabled");
$.each(list, function () {
$(dropDownId).append($("<option>/option>").val(this['Value']).html(this['Text']));
});
}
}
</script>
}
Models
[Required]
[Display(Name = "StateId")]
public string StateId { get; set; }
[Required]
[Display(Name = "States")]
public List<SelectListItem> States = new List<SelectListItem>();
public string value { get; set; }
Controller
public JsonResult AjaxMethod(string type, string value)
{
PersonModel model = new PersonModel();
//Second DropDownList
model.States = PopulateDropDown(" SELECT * FROM `tbl_1` " +
" WHERE `Node_Code` = '" + value + "';", "Node_Name", "Node_Code");
//GET value tod textbox GPS
GetGps(value);
return Json(model);
}
public JsonResult GetGps(string value)
{
return Json(GetGpsById(value), JsonRequestBehavior.AllowGet);
}
private static string GetGpsById(string value)
{
string sql;
List<SelectListItem> items = new List<SelectListItem>();
string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
sql = string.Format("SELECT CONCAT(`LAT`, ' - ', `LON`) AS GPS FROM `tbl_1` WHERE Node_Code = #Id");
using (MySqlCommand cmd = new MySqlCommand(sql))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Id", value);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
return name;
}
}
}
[HttpPost]
public ActionResult Index(PersonModel person)
{
//First DropDownList
person.Countries = PopulateDropDown(" SELECT * FROM `tbl_master`;", "Name_City", "Name_code");
return View(person);
}
private static List<SelectListItem> PopulateDropDown(string query, string textColumn, string valueColumn)
{
List<SelectListItem> items = new List<SelectListItem>();
string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr[textColumn].ToString(),
Value = sdr[valueColumn].ToString()
});
}
}
con.Close();
}
}
return items;
}
Update
public JsonResult AjaxMethod(string type, string value)
{
PersonModel model = new PersonModel();
//Second DropDownList
model.Cities = PopulateDropDown(" SELECT * FROM `tbl_1` " +
" WHERE `Node_Code` = '" + value + "';", "Node_Name", "Node_Code");
//GET value tod textbox GPS
model.GPS = GetGps(value).ToString();
return Json(model);
}
Your problem is you never use the GPS property of your model:
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
PopulateDropDown(dropDownId, list); // You set dropDownId, might as well use it
$("#GPS").val(response.GPS); // Added to set text in textbox
break;
}
}
and in your controller,
model.GPS = GetGpsById(value); // this is already a string
instead of
model.GPS = GetGps(value).ToString(); // this is the string representation of a jsonified string

DropDownList bind from web service Not passing data source when Edit in asp.net

I am using web service to bind data in DropDownList when I Add New data drop down list working fine, but when I Edit mode drop data source not fill. so the question is how to fill data source when I am using web service to bind web service.
Html:
<asp:DropDownList ID="cmbFlightNo" class="form-control" runat="server" DataValueField="mFlightNo" DataTextField="mFlightNo" AppendDataBoundItems="true">
</asp:DropDownList>
webservies
[WebMethod]
public Airline_Flights[] Loadetails(string StuID)
{
string Conec = ConfigurationManager.ConnectionStrings["BriskCargo"].ConnectionString;
SqlConnection con = new SqlConnection(Conec);
con.Open();
SqlDataAdapter da = new SqlDataAdapter("Select FlightNo from AirLine_Flights where ALCode='" + StuID + "' and IsActive=1", con);
DataTable st = new DataTable();
da.Fill(st);
List<Airline_Flights> details = new List<Airline_Flights>();
foreach (DataRow dtrow in st.Rows)
{
Airline_Flights obj = new Airline_Flights();
obj.mFlightNo = dtrow["FlightNo"].ToString();
details.Add(obj);
}
JavaScriptSerializer ser = new JavaScriptSerializer();
return details.ToArray();
}
JQuery code to fill when change when fire.
function Load_Regno() {
var StuID = document.getElementById('ContentPlaceHolder1_cmbAirlines').value;
$.ajax(
{
type: "POST",
contentType: "application/json;charset=utf-8",
url: "AirlinesDropDown.asmx/Loadetails",
data: JSON.stringify({StuID: StuID }),
dataType: "json",
success: function (data) {
var theDropDown = document.getElementById("ContentPlaceHolder1_cmbFlightNo");
theDropDown.length = 0;
$.each(data.d, function (key, value) {
$("#ContentPlaceHolder1_cmbFlightNo").append($("<option></option>").val(value.mFlightNo).html(value.mFlightNo));
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 0) {
alert(' Check Your Network.');
} else if (XMLHttpRequest.status == 404) {
alert('Requested URL not found.');
} else if (XMLHttpRequest.status == 500) {
alert('Internel Server Error.');
} else {
alert('Unknow Error.\n' + XMLHttpRequest.responseText);
}
}
});
return false;
}
[WebMethod]
public Airline_Flights[] Loadetails(string StuID)
{
var flightsList = GetFlightListByStuID(string StuID);
return selectedFlights.Select(x => x.FlightNo).ToArray();
}
// could be in another data access class etc.
private List<Airline_Flights> GetFlightListByStuID(string StuID)
{
List<Airline_Flights> selectedFlights = new List<Airline_Flights>();
string connectionString = ConfigurationManager.ConnectionStrings["BriskCargo"].ConnectionString;
// SQL with parameter
string commandString = #"
SELECT FlightNo
FROM AirLine_Flights
WHERE ALCode = #StuID AND IsActive=1
";
// use IDisposable here so it closes and garbage collects automatically
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(commandString))
{
// check the length and type here...
command.Parameters.Add("#StuID",SqlDbType.NVChar, 25).Value = StuID;
command.CommandType = CommandType.Text;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
flightsList.Add(new Airline_Flights{ FlightNo= reader["FlightNo"].ToString()});
}
}
}
}
return selectedFlights;
}
JavaScript
function Load_Regno() {
var StuID = document.getElementById('ContentPlaceHolder1_cmbAirlines').value;
$.ajax({
type: "POST",
contentType: "application/json",
url: "AirlinesDropDown.asmx/Loadetails",
data: {StuID: StuID},
dataType: "json"
})
.done(function(data) {
// verify data
alert(JSON.stringify(data));
// or
console.log(data);
var theDropDown = $("ContentPlaceHolder1_cmbFlightNo");
theDropDown.html(""); // clear old options
var options = [];
$.each(data.d, function(key, value) {
var opt = ("<option></option>").val(value.FlightNo).html(value.FlightNo))
options.push(opt);
});
$.each(options,function(v){theDropDown.append(v);});
})
.fail(function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 0) {
alert('Check Your Network.');
} else if (XMLHttpRequest.status == 404) {
alert('Requested URL not found.');
} else if (XMLHttpRequest.status == 500) {
alert('Internal Server Error.');
} else {
alert('Unknown Error.\n' + XMLHttpRequest.responseText);
}
}
});
return false;
}

Recover id in display list using combobox

i need to recover the id of element selected in combobox in dev express
and this is the code of combobox:
#Html.DevExpress().ComboBox(
settings =>
{
settings.Name = "comboBox4";
settings.Width = 180;
settings.SelectedIndex = 0;
settings.Properties.DropDownWidth = 550;
settings.Properties.DropDownStyle = DropDownStyle.DropDownList;
settings.CallbackRouteValues = new { Controller = "Editors", Action = "MultiColumnComboBoxPartial" };
settings.Properties.CallbackPageSize = 30;
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
settings.Properties.TextFormatString = "{1}";
settings.Properties.ValueField = "Id";
settings.Properties.ValueType = typeof(string);
settings.Properties.Columns.Add("Id", "Id", 130).SetColVisible(false);
// settings.Properties.Columns.Add("Id", "Id", 130).SetColVisibleIndex(1);
settings.Properties.Columns.Add("Nom", "Nom", 130);
settings.Properties.Columns.Add("Prenom", "Prenom", Unit.Percentage(100));
settings.Properties.Columns.Add("DateNaissance", "DateNaissance", 60);
settings.Properties.Columns.Add("CodeClient", "CodeClient", 100);
}
).BindList(client).GetHtml()
and this the method ajax how i put the value of any custom with ajax:
function Addprojet() {
debugger;
var nom = $("#nom2_I").val();
var description = $("#Description_I").val();
var client = $("#comboBox4_I").val();
var chef = $("#chefid_I").val();
var complexite = $("#comboBox1_I").val();
var taille = $("#comboBox2_I").val();
var datedebut = $("#datedebut_I").val();
$.ajax({
url: "/Projet/AjouterProjet?nom=" + nom + "&description=" + description + "&client=" + client + "&chef=" + chef + "&complexite=" + complexite + "&taille=" + taille + "&datedebut=" + datedebut, // /Controlleur/Action
type: "POST",
dataType: 'text',
//data : {Nom: nom},
success: function (responseText) {
debugger;
if (responseText == "True") {
location.replace("/Client/listeclients");
}
else {
alert("error");
}
}
});
}
</script>
how can i resolve this issue because i need to recover the id of client without displaying in the list in the combobox
can semeone help me to fix it .

how to display the search result from the grid using jquery?

i have my jquery like,
$(document).ready(function () {
$('#NotAllotedStudentsGrid').jtable({
title: 'Allot to Students below',
paging: true,
pageSize: 5,
sorting: true,
defaultSorting: 'Name ASC',
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkbo.xes on first column
actions: {
listAction: '#Url.Action("NotAllotedStudentsList")',
//deleteAction: '#Url.Action("DeleteStudent")',
//updateAction: '#Url.Action("UpdateStudent")',
//createAction: '#Url.Action("CreateStudent")'
},
fields: {
UserNo: {
key: true,
create: false,
edit: false,
list: false
},
Name: {
title: 'Name',
width: '15%'
},
Batch: {
title: 'Batch',
},
EmailAddress: {
title: 'Email address',
},
ContactNo: {
title: 'Contact No',
type: 'textarea',
}
}
});
//Load student list from server
$('#NotAllotedStudentsGrid').jtable('load');
$('#SearchFor').button().click(function () {
var SearchForValue = $("#NotAllotedStudentsList").val();
var StudentInputTypeValue = $("#InputType").val();
var options = {};
options.type = "POST";
options.url = "/Dashboard/NotAllotedStudentsList/";
options.data = JSON.stringify({ model: { SearchFor: SearchForValue, StudentInputType: StudentInputTypeValue } });
options.dataType = "json";
options.contentType = "application/json";
$.ajax(options);![enter image description here][1]
});
i have my controller like,
public ActionResult NotAllotedStudentsList(AllotQuestionSet model,int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
{
List<TutorStudentsGridModel> tutorStudentsGridModelList = new List<TutorStudentsGridModel>();
User userDetails = _sessionHelper.Get<User>(KrackemSessionConstants.UserDetails);
StudentResponse studentListResponse = new StudentResponse();
int questionSetNo = Int32.Parse(_sessionHelper.Get<string>(KrackemSessionConstants.QuestionSetNo));
if (model.SearchFor == null)
{
StudentRequest studentRequest = new StudentRequest
{
TutorUserNo = userDetails.UserNo,
QuestionSetNo = questionSetNo
};
studentListResponse = _questionSetServiceHelper.GetNotAllottedStudentsByTutorNo(studentRequest);
}
//Get Not Allotted Students By Name
if (model.SearchFor != null && model.StudentInputType == StudentInputType.Name)
{
StudentRequest studentRequest = new StudentRequest
{
TutorUserNo = userDetails.UserNo,
QuestionSetNo = questionSetNo,
InputString = model.SearchFor
};
studentListResponse = _questionSetServiceHelper.GetNotAllottedStudentsByName(studentRequest);
}
foreach (StudentContract studentDetails in studentListResponse.StudentList)
{
TutorStudentsGridModel tutorStudentsGridModel = MappingEngineFactory.GetMappingEngine().Map<StudentContract, TutorStudentsGridModel>(
studentDetails);
tutorStudentsGridModel.Id = studentDetails.UserNo;
tutorStudentsGridModelList.Add(tutorStudentsGridModel);
}
if (jtSorting != null)
tutorStudentsGridModelList = ControllerHelper.SortList(jtSorting, tutorStudentsGridModelList);
tutorStudentsGridModelList = jtPageSize > 0 ? tutorStudentsGridModelList.Skip(jtStartIndex).Take(jtPageSize).ToList() : tutorStudentsGridModelList.ToList();
return Json(new { Result = "OK", Records = tutorStudentsGridModelList, TotalRecordCount = studentListResponse.StudentList.Count() });
}
Initially, the page with grid get loaded from server with the list of students with fields i.name ii.batch iii.email iv.contact_no, after selecting "name" from dropdown and entered a name in textbox then clicking the search button for search , the search results should display. But its displaying old grid. kindly tell me how to display the search result from the grid using jquery.

sorting in asp.net

var store = new FMP.AspNetJsonStore({
fields: [
{ name: 'AssetID' },
{ name: 'AssociationID' },
{ name: 'Image' },
{ name: 'StatusName' },
{ name: 'ModelName' },
{ name: 'IPAddress' },
{ name: 'InScope', type: 'boolean' },
{ name: 'ServicePlanName' },
{ name: 'PricePlanName' },
{ name: 'PricePlanDescription' },
{ name: 'Program' },
{ name: 'ServicePlanID' },
{ name: 'Customer' },
{ name: 'Black', type: 'float' },
{ name: 'Cyan', type: 'float' },
{ name: 'Magenta', type: 'float' },
{ name: 'Yellow', type: 'float' },
{ name: 'BlackPct' },
{ name: 'CyanPct' },
{ name: 'MagentaPct' },
{ name: 'YellowPct' },
{ name: 'PrinterMarkerSupplies' },
{ name: 'PageCount' },
{ name: 'BlackImpressions' },
{ name: 'ColorImpressions' },
{ name: 'PricePlanID' },
{ name: 'ResponsibilityForAction' },
{ name: 'PrinterSerialNumber' }
],
totalProperty: "TotalCount",
autoLoad: { params: { start: 0, limit: myPageSize} },
//autoLoad: true,
proxy: new Ext.data.HttpProxy({
// Call web service method using GET syntax
url: 'GetPrintersGrid.asmx/buildGrid',
// Ask for Json response
headers: { 'Content-type': 'application/json' },
method: "GET"
}),
remoteSort: true,
//sortInfo: { field: 'PageCount', direction: "DESC" },
groupField: 'Customer',
root: 'Records'
});
store.setDefaultSort('PageCount', 'DESC');
Here is the web service i used
public PagedResult<FMPAsset> buildGrid(int start, int limit, string sortfield, string dir)
{
var a=5;
Guid AccountID = (Guid)Session["AccountID"];
//string sortdir;
//if( dir == "DESC")
//{
// sortdir = dir.Substring(0, 4).Trim().ToUpper();
//}
//else
//{
// sortdir = dir.Substring(0, 3).Trim().ToUpper();
//}
string SortExpression = sortfield + " " + (!String.IsNullOrEmpty(dir) ? dir : String.Empty);
//string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "' order by a.PageCount = '" + + "'";
string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "' Order By a."+SortExpression;
//string whereClause = "SELECT value a , ROW_NUMBER() OVER(ORDER BY"
// + " " + SortExpression
// + ") As RowNumber FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'"
// + AccountID + "'";
//string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "'";
List<FMPAsset> fmpAssets = new List<FMPAsset>();
using (XSPAssetModel.XSPAssetEntities assetEntities = new XSPAssetEntities(b.BuildEntityConnectionString1("XSMDSN")))
{
ObjectQuery<XSP_AssetList_V> assets = new ObjectQuery<XSP_AssetList_V>(whereClause, assetEntities);
//var assetOrder = assets.OrderBy(x => x.StatusName).ToList();
var assetPage = assets.Skip(start).Take(limit);
//var totalAssetCount = assets.Count();
currentAssets = assetPage.ToList();
int currentAssetsCount = currentAssets.Count;
string imgprefix = System.Configuration.ConfigurationManager.AppSettings["ImgPrefix"];
char[] separators = { '/' };
string appname = "";
int lastloc = imgprefix.Substring(0, imgprefix.Length - 1).LastIndexOfAny(separators);
if (lastloc > 6)
{
appname = imgprefix.Substring(lastloc + 1);
}
FMPAsset asset = new FMPAsset();
//StreamWriter sw = new StreamWriter("C:\\test.txt");
XSPPrinterMarkerSupplyModel.XSPPrinterMarkerSupplyEntities markerCtx =
new XSPPrinterMarkerSupplyModel.XSPPrinterMarkerSupplyEntities(b.BuildEntityConnectionString1("XSMDSN"));
for (int x = 0; x < currentAssetsCount; x++)
{
asset = new FMPAsset();
asset.AssetID = currentAssets[x].AssetID.ToString();
asset.PricePlanID = currentAssets[x].PricePlanID.ToString();
asset.AssociationID = currentAssets[x].AssociationID;
asset.ModelName = currentAssets[x].ModelName;
asset.ResponsibilityForAction = currentAssets[x].ResponsibilityForAction;
asset.IPAddress = (String.IsNullOrEmpty(currentAssets[x].PrinterIPAddress)) ? "No IP" : currentAssets[x].PrinterIPAddress; ;
if (currentAssets[x].InScope)
{
asset.InScope = b.GetString("SDE_YES");
}
else
{
asset.InScope = b.GetString("SDE_NO");
}
asset = SetStatus(appname, asset, x);
asset.PricePlanName = currentAssets[x].Program;
asset.PricePlanDescription = currentAssets[x].PricePlanDescription;
asset.ServicePlanName = currentAssets[x].ServicePlanName;
if (currentAssets[x].PrinterSerialNumber != null)
{
asset.PrinterSerialNumber = currentAssets[x].PrinterSerialNumber;
}
else
{
asset.PrinterSerialNumber = "-";
}
//sw.WriteLine("ChargebackDescription: " + DateTime.Now.Millisecond);
if (this.b.UseChargebackDescription
&& !String.IsNullOrEmpty(currentAssets[x].CustomerChargebackDescription)
&& currentAssets[x].CustomerChargebackDescription != "Generated by OUT Integration")
{
asset.Customer = currentAssets[x].CustomerChargebackDescription;
if (asset.Customer.IndexOf(Environment.NewLine) > -1)
{
asset.Customer =
asset.Customer.Substring(0, asset.Customer.IndexOf(Environment.NewLine));
}
}
else
{
asset.Customer = currentAssets[x].CustomerChargeBackEntryName;
}
if (this.b.UsePricePlanDescription && !String.IsNullOrEmpty(currentAssets[x].PricePlanDescription))
{
asset.Program = currentAssets[x].PricePlanDescription;
if (asset.Program.IndexOf(Environment.NewLine) > -1)
{
asset.Program =
asset.Program.Substring(0, asset.Program.IndexOf(Environment.NewLine));
}
}
else
{
asset.Program = currentAssets[x].Program;
}
asset.BlackPct = -3;
asset.CyanPct = -3;
asset.MagentaPct = -3;
asset.YellowPct = -3;
Guid id = currentAssets[x].AssetID;
asset = SetCMYKvalues(asset, x);
BuilldImpressionsValues(currentAssets[x], ref asset);
fmpAssets.Add(asset);
}
//CommonGrid1.ApplyUserPreferences();
//JavaScriptSerializer json = new JavaScriptSerializer();
//string JsonArray = json.Serialize(fmpAssets);
//string ArrayDeclaration = string.Format("var arr = {0};", JsonArray);
//Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "fmpAssets", ArrayDeclaration, true);
//assetEntities.Dispose();
var totalAssetCount = assets.Count();
var y = new PagedResult<FMPAsset>();
y.Records = fmpAssets;
y.TotalCount = totalAssetCount;
return y;
// CommonGrid1.BindDataSource(SortByStatusName(fmpAssets));
}
}
I am getting an error saying:
{"Message":"Invalid JSON primitive:
DESC.","StackTrace":" at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n
at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32
depth)\r\n at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String
input, Int32 depthLimit,
JavaScriptSerializer serializer)\r\n
at
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer
serializer, String input, Type type,
Int32 depthLimit)\r\n at
System.Web.Script.Services.RestHandler.GetRawParamsFromGetRequest(HttpContext
context, JavaScriptSerializer
serializer, WebServiceMethodData
methodData)\r\n at
System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData
methodData, HttpContext context)\r\n
at
System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext
context, WebServiceMethodData
methodData)","ExceptionType":"System.ArgumentException"}
Can anyone help me in this issue?
Sure Here is the JSON store
Ext.ns("FMP");
FMP.AspNetJsonReader = Ext.extend(Ext.data.JsonReader, {
read: function(response) {
// Assuming ASP.NET encoding - Data is stored as
var json = response.responseText;
var o = Ext.decode(json);
if (!o) {
throw { message: "AspNetJsonReader.read: Json object not found" };
}
if (!o.d) {
throw { message: "AspNetJsonReader.read: Root element d not found" };
}
return this.readRecords(o.d);
}
});
FMP.AspNetJsonStore = Ext.extend(Ext.data.GroupingStore, {
/**
* #cfg {Ext.data.DataReader} reader #hide
*/
constructor: function(config) {
FMP.AspNetJsonStore.superclass.constructor.call(this, Ext.apply(config, {
reader: new FMP.AspNetJsonReader(config)
}));
}
});

Categories

Resources