Getting Large JSON Data Make Browser Rendering Issues - c#

I have approx 100000 rows in each of 4 database tables and using web api async Action to get the data through ADO.NET Datasets. I am using 2 drop downs and 2 grid views to load 100000 entries into them.
Following is one of the four controllers I am using to get the Data.
public class OrdersDCController : ApiController
{
public async Task<int> GetOrdersDC()
{
return await DCOrderHelper.GetOrdersCount();
}
// GET api/Orders
public async Task<List<OrderDTO>> GetOrdersDC(int offset, int fetchRecords)
{
return await DCOrderHelper.GetAllOrders(offset, fetchRecords);
}
}
And the following ajax call is
///The Button Click which makes an ajax call to Web API
$("#btngetdata").click(function () {
offset = 0;
custRecordsRendered = 0;
$.when(
$.ajax({
type: 'GET',
url: "/api/OrdersDC",
datatype: "application/json; charset=utf-8",
success: function (data) {
totalRecords = data;
fetch = parseInt(totalRecords / 10);
$("#progressBar").progressbar(0);
//alert(fetch);
getDataAtOffset();
}
})
);
function getDataAtOffset() {
$.ajax({
type: 'GET',
url: "/api/OrdersDC?offset=" + offset * fetch + "&fetchRecords=" + fetch,
datatype: "application/json; charset=utf-8",
success: function (customerData) {
var customers = [];
customers = getDataInArray(customerData); //Convert the JSON response into an Array
var custCount = customers.length;
for (var i = 0; i < custCount; i++) {
displayCustomerInformation($("#customerTemplate").render(customers[i]));
custRecordsRendered = custRecordsRendered + 1;
}
updateProgress();
if (offset * fetch < totalRecords) {
offset = offset + 1;
getDataAtOffset();
}
}
});
}
function updateProgress() {
var progress = $("#progressBar").progressbar("option", "value");
if (progress < 10) {
//Increase the value of the progress by 1
$("#progressBar").progressbar("option", "value", progress + 1);
}
$("#completeCount").text(custRecordsRendered + "/" + totalRecords + " Records Rendered");
}
function displayCustomerInformation(ele) {
$("#tblemp").append(ele);
}
///Method to convertt the JSON data into an array
function getDataInArray(array) {
var cust = [];
$.each(array, function (i, d) {
cust.push(d);
});
return cust;
}
});
I actually wanted to make my Browser UI not getting stucked when data is getting loaded. But Browser is having rendering issues when this much data get loads into the browser. Any help will be appreciated.
Thanks

Related

Parameter in my C# controller read as null from the AJAX call

I'm trying to take input from Users through a checkbox and store it in a table in my SQL DB, I've created all the link properly and my post AJAX call works well because I was able to receive information in my DB. The problem is the parameter received in my controller is receiving a null value which is storing a null value in my table, I know that my checkbox is pulling the right information because im printing it before hand but I feel like my AJAX setup may not be stringifying it properly.
$("#submitButton").click(function() {
var results = {};
$questions = $('#optionData');
for (i = 1; i < 6; i++) {
if ($questions.find('#option' + i).prop('checked')) {
results['option' + i] = $questions.find('#option' + i).val();
}
newResult = JSON.stringify(results)
};
console.log(newResult);
$.ajax({
url: "/Home/SaveData",
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: (newResult),
success: function(data) {
if (data == null) {
alert("Something went wrong");
}
},
failure: function(data) {
alert(data.dataText);
},
error: function(data) {
alert(data.dataText);
}
});
});
[HttpPost]
public ActionResult SaveData(string Options)
{
dataInsertion dataInsertion = new dataInsertion
{
// questionID = object.QuestionId,
options = Options,
// },
// companyID = object.companyID
};
try
{
if (ModelState.IsValid)
{
DB.dataInsertions.Add(dataInsertion);
DB.SaveChanges();
// RedirectToAction("Home");
}
}
catch (Exception e)
{
Console.WriteLine("error" + e);
}
return Json(new { sucess = "true" });
}

How to load new data after click next or back Fullcalendar

I am using Fullcalendar plugin which is integrated with my ASP.NET MVC project. My main task consists of creating a schedule of reservations. I have written the code which is responsible for displaying events("Buttons") for specific date, and it works fine!. Code below:
var calendar = $("#calendar").fullCalendar({
weekends: false
, lang: 'pl',
header: {
left:'',
center: 'title',
right: 'today prev,next'
}, height: 630, week: true, columnFormat: 'dd M/D', minTime: '8:00', maxTime: '20:00', selectable: true,
allDaySlot: false, eventColor: '#F6A828',
events: function (start, end, timezone, callback) {
$.ajax({
url: '/Dentist/GetEvents/',
type: 'POST',
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//
}
});
},
})
$('#calendar').fullCalendar('changeView', 'agendaWeek');
and method GetEvents in C#
public JsonResult GetEvents()
{
if (Session["DoctorID"] == null)
{
return Json(new { redirectUrl = Url.Action("Terminarz", "Recepcjonista"), isRedirect = true });
}
var listEvent = new List<CallendarEvent>();
List<CallendarEvent> list = TermRepository.GetAllEventsByDoctorId((int)Session["DoctorID"]);
int licznik = 1;
foreach (var item in list)
{
int count = Size(item.id, item.From, item.To);
for (int i = 0; i < count; i++)
{
listEvent.Add(new CallendarEvent()
{
id = licznik,
day = item.day,
Title = item.Title,
From = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30),
To = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddMinutes(30)
});
licznik++;
}
}
var listEvent2 = from l in listEvent
select new
{
id = l.id,
//day = l.day,
//Title = l.Title,
start = l.From,
end = l.To,
color = "#88CD23"
};
return Json(listEvent2, JsonRequestBehavior.AllowGet);
}
and now I would like to handle next and back buttons and change start date, end +7 day. I wrote something like this, but doesn't work
C#
public JsonResult GetEventsAdd(int move)
{
//all the same method as in GetEvents, but added days
listEvent.Add(new CallendarEvent()
{
id = licznik,
day = item.day,
Title = item.Title,
From = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddDays(move),
To = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddMinutes(30).AddDays(move)
});
licznik++;
}
}
//all the same method as in GetEvents
return Json(listEvent2, JsonRequestBehavior.AllowGet);
}
and script was changed
events: function (start, end, timezone, callback) {
var data = { "move": 7 }
$.ajax({
url: '/Dentist/GetEvents/',
type: 'POST',
//data: JSON.stringify(calendar),
//datatype: "json",
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//
}
});
$(".fc-next-button").one("click", function () {
$.ajax({
url: '/Dentist/GetEventsAdd/',
type: 'POST',
data: JSON.stringify(data),
datatype: "json",
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//$('#calendar').fullCalendar('refetchEvents');
}
});
});
how can I get such a solution?
The AJAX call that fullcalendar makes passes the start and end date range for the current view. It will then call that again, only if it doesn't have the date stored.
so in your /Dentist/GetEvents/
grab the "GET" variables: "START" and "END".
return the events that are in that range.
then simply use the native 'next', 'prev' buttons from fullcalendar and let it do its thing.

Posting JSON object to asp.net server

i am trying to post some json data to to my asp.netserver on my localhost. The page to receive the code should be the master page, however i tried that and got "Error 403: Forbidden" so i tried my hands on a web service instead and now i am having a whole load of other issues. My main issue is that i could do this rather simply in PHP but i have no idea how to go about this in ASP.NET.
This is my js file:
// Get User Login Credentials
function authenticate() {
$(document).ready(function () {
var user = $('.login-box form #txtLoginUsername').val().trim();
var pass = $('.login-box form #txtLoginPass').val().trim();
// alert(user + " : " + pass);
$.ajax({
type: "POST",
url: "postback.asmx/Verify",
data: {
user: user,
pass: pass
},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function() {
if (response)
{
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () {});
}
}
});
});
}
Now i call this function on a button click event, i do not add my server code because it comprises of several lines of code i picked up from the net and tried to mash up to get my page to work, which it didn't. I would like to know a simple appropriate method of getting JSON objects from a post and return a value/array from my server.
Please i do not wish to use any asp.net server controls for certain reasons i am unable to disclose, but i have been restricted from using such controls.
You can´t put your WebMethod in an masterPage. Ajax is client side and you are getting the same error if you tried to acess site.master in your browser.
"Description: The type of page you have requested is not served because it has been explicitly forbidden. The extension '.master' may be incorrect. Please review the URL below and make sure that it is spelled correctly. "
You can implement your WebMethod in other file .aspx and call by ajax.
I wrote an little example.
cs
[WebMethod(enableSession: true)]
public static void Verify(string user, String pass)
{
throw new Exception("I´m here");
}
js
function authenticate() {
$(document).ready(function () {
var user = $('#txtLoginUsername').val().trim();
var pass = $('#txtLoginPass').val().trim();
// alert(user + " : " + pass);
var data = {};
data.user = user;
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: JSON.stringify({
user: user,
pass: pass
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
if (response) {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});
});
}
pay attention how Json is passing to data
data: JSON.stringify({
user: user,
pass: pass
}),
To call webservice, try pass json this way.
When you call web service there are same error message in browser´s console?
I think this is will help you.
You can use JSON.stringify() method as explained in follow
var jsonData=your Jason data;
Data:JSON.stringify(jsonData)
courtsey:
http://www.dotnetlines.com/forum/tabid/86/forumid/6/postid/72/scope/posts/Default.aspx#72
You can do like this.
[WebMethod]
public string Verify(string user,string pass)
{
//DataTable dt = YourMethod_ReturningDataTable();
//retrun dt.toJson();
//But in your case
bool IsAllowedtoLogin = true;
return IsAllowedtoLogin.toJson();
}
For this (toJson) method you have create a static class.This will convert even datatable to json format.
public static string toJson(this DataTable dataTable)
{
string[] StrDc = new string[dataTable.Columns.Count];
string HeadStr = string.Empty;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
StrDc[i] = dataTable.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + dataTable.TableName + "\" : [");
for (int i = 0; i < dataTable.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dataTable.Columns.Count; j++)
{
TempStr = TempStr.Replace(dataTable.Columns[j] + j.ToString() + "¾", dataTable.Rows[i][j].ToString());
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}
Note that data parameters are case sensitive. i.e user , pass .
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: "{'user':'"+yourvariable+"','pass':'"+yourvariable+"'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
data = JSON && JSON.parse(data.d) || $.parseJSON(data.d);
if (data == "true") {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});

update a variable of Javascript file from my c# function

I have a function in c# that gets a budget and Id-s of ads and updates all the budgets of these ads to be with budget value of budget:
[HttpPost]
public ActionResult UpdateAdsBudgets(string budget, string[] Ids)
{
ServerResult serverResult = null;
try
{
int numOfSuccess = 0;
for (int i = 0; i < Ids.Length; i++)
{
serverResult = UpdateAdBudget(Ids[i]);
if (serverResult.ServerResultState == ServerResultState.SUCCESS)
{
numOfSuccess++;
}
}
}
}
I called this function in my js file:
$.ajax({
dataType: 'json',
type: "POST",
traditional: true,
url: "/AdsController/UpdateAdsBudgets",
data: { budget: budget, Ids: adsIds },
success: function (serverResult) {
},
error: function (exception) {
}
});
Is there an option to display a message with an info of the called function? I mean to: 2/5 ads were updated, where 2 is numOfSuccess (the variable of my c# file) and 5 is: adsIds.length.
I know I can do a lot of ajax calling (for each ad) and then count it in the succes, but is there an option that the function of c# will update online a variable in my js file? (assuming the variable: "numberOfSuccededAds").
any help appreciated!
Why not just return Json(YOR_DATA_YEAR) and handle it in success handler of your JavaScript ajax function.
public ActionResult UpdateAdsBudgets(string budget, string[] Ids)
{
ServerResult serverResult = null;
try
{
int numOfSuccess = 0;
for (int i = 0; i < Ids.Length; i++)
{
serverResult = UpdateAdBudget(Ids[i]);
if (serverResult.ServerResultState == ServerResultState.SUCCESS)
{
numOfSuccess++;
}
}
}
return Json(YOUR_DATA);
}
You can return a JsonResult from your controller like so:
[HttpPost]
public ActionResult UpdateAdsBudgets(string budget, string[] Ids)
{
ServerResult serverResult = null;
try
{
int numOfSuccess = 0;
for (int i = 0; i < Ids.Length; i++)
{
serverResult = UpdateAdBudget(Ids[i]);
if (serverResult.ServerResultState == ServerResultState.SUCCESS)
{
numOfSuccess++;
}
}
}
return Json(numOfSuccess);
}
You can then do an alert in your Javascript to inform the user.
$.ajax({
dataType: 'json',
type: "POST",
traditional: true,
url: "/AdsController/UpdateAdsBudgets",
data: { budget: budget, Ids: adsIds },
success: function (serverResult) {
alert(serverResult + "/" + adsIds.length + " ads were updated");
},
error: function (exception) {
} });
is there an option that the function of c# will update online a variable in my js file
No, your ASP.NET service knows absolutely nothing about the client your only option is to pass the information it needs back as part of the post e.g.
[HttpPost]
public ActionResult UpdateAdsBudgets(string budget, string[] Ids)
{
...
return Json(numOfSuccess);
}
Then in your success callback
success: function (serverResult) {
alert(serverResult+ '/' + adsIds.length + ' ads were updated');
}

JQuery.Ajax and MVC4

I have a need to call a method on my controller to return a complex type using the JQuery.Ajax method.
function CallMethodTest(Id) {
//alert(Id);
$.ajax({
type: 'POST',
url: '/MyController/MyMethod',
dataType: "json",
contentType: "application/json; charset=utf-8",
//data: "{'Id': '" + Id + "'}",
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
[System.Web.Services.WebMethod]
public string MyMethod()
{
return "ABC"; // Gives me the error on the first alert of "200" and the second alert "Syntax Error: Invalid Character"
return "1"; // Works fine
}
As the code explains, if I return an integer (as a string) the return works and I alert "1", however, If I try and return any alpha characters I get the alerts shown in the comments of MyMethod.
From your code, it looks as though you are returning the value from your Controller url: "/MyController/MyMethod"
If you are returning the value from your controller, then get rid of the [System.Web.Services.WebMethod] code and replace it with this ActionResult
[HttpPost]
public ActionResult MyMethod(){
return Json("ABC");
}
Also, if you are ever going to call a method in your controller via GET then use
public ActionResult MyMethod(){
return Json("ABC", JsonRequestBehavior.AllowGet);
}
In View You use the following code,
function ItemCapacity() {
$.ajax({
type: "POST",
url: '#Url.Action("ItemCapacityList", "SalesDept")',
data: { 'itemCategoryId': itemCategoryIds },
dataType: 'json',
cache: false,
success: function (data) {
var capacityCounter = 0;
var capacitySelected = "";
for (var i = 0; i < rowsCount; i++) {
var tr = $("#gvSpareSetItemsDetails tbody tr:eq(" + i + ")");
var categoryId = $(tr).find('td:eq(5)').text();
var isSelectOrNot = $(tr).find('td:eq(1)').find('select');
if (isSelectOrNot.is('select')) {
$.map(data, function (item) {
if (categoryId == item.ItemCategoryID) {
isSelectOrNot.get(0).options[isSelectOrNot.get(0).options.length] = new Option(item.CapacityDescription, item.ItemCapacityID);
capacityCounter = capacityCounter + 1;
capacitySelected = item.ItemCapacityID;
}
});
if (capacityCounter == 1) {
isSelectOrNot.val(capacitySelected);
}
capacityCounter = 0;
capacitySelected = "";
}
}
},
error: function () { alert("Connection Failed. Please Try Again"); }
});
}
}
In the Controller Use the following Code,
public JsonResult ItemCapacityList(string itemCategoryId)
{
List<ItemCapacity> lsItemCapacity = new List<ItemCapacity>();
string[] itemCategory = itemCategoryId.Split('#');
int itemCategoryLength = itemCategory.Length, rowCount = 0;
string itemCategoryIds = string.Empty;
for (rowCount = 0; rowCount < itemCategoryLength; rowCount++)
{
itemCategoryIds += "'" + itemCategory[rowCount].Trim() + "',";
}
itemCategoryIds = itemCategoryIds.Remove(itemCategoryIds.Length - 1);
lsItemCapacity = salesDal.ReadItemCapacityByCategoryId(itemCategoryIds);
return new JsonResult { Data = lsItemCapacity };
}

Categories

Resources