I am facing a problem in rendering events from a SQL Server database. All events are getting fetched using this code but not getting displayed in my calendar, so can anyone please help me?
.cshtml code:
events: function(start, end, callback) {
debugger;
var startdate=start.format('DD-MM-YYYY HH:mm'),
enddate=end.format('DD-MM-YYYY HH:mm'),
params={'start_time':startdate,'end_time':enddate};
$.ajax({
type: 'GET',
url: '#Url.Action("GetAllEvents","Base")',
success: function (data) {
alert("hello");
}
});
}
,
my controller code:
public static List<Task_has_UsersModel> LoadAllTasks(double start, double end)
{
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
var sql = "SELECT * from task_has_users";
var data = Database.Open("DefaultConnection").Query(sql);
List<Task_has_UsersModel> result = new List<Task_has_UsersModel>();
foreach (var item in data)
{
Task_has_UsersModel model = new Task_has_UsersModel();
model.Task_Id = Convert.ToInt32(item.Task_Id);
model.Project_Id = Convert.ToInt32(item.Project_Id);
model.start_time = item.start_time;
model.end_time = item.end_time;
result.Add(model);
}
return result;
}
[HttpPost]
public JsonResult GetAllEvents(double start, double end)
{
var ApptListForDate = LoadAllTasks(start,end);
var eventList = from e in ApptListForDate
select new
{
id=e.Task_Id,
name=e.Project_Id,
start=e.start_time.ToString(),
end=e.end_time.ToString(),
allDay=false,
color = "#008000",
//allDay=false,
className= "label-important" ,
};
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
private static DateTime ConvertFromUnixTimestamp(double timestamp)
{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
}
I have tried with (double start,double end ) still my events are not getting displayed in calendar
Finally after 3 days of hard work , i have done this.... No need to write anything in events , just call a function , it will automatically appends the date range and all you are done................... thanks
.cshtml code:
events:'GetAllEvents',
eventLimit: 50,
editable: true,
droppable: true,
// timeFormat: 'hh:mm-h:mma ',
timeFormat: 'hh:mma ',
displayEventEnd : true,
my controller code:
public static List<Task_has_UsersModel> LoadAllTasks(string start, string end,string uname)
{
UsersContext db = new UsersContext();
var uid = (from i in db.UserProfiles
where i.UserName == uname
select i.UserId).FirstOrDefault();
int userId = Convert.ToInt32(uid);
// var culture = System.Globalization.CultureInfo.CurrentCulture;
var sql = "SELECT * from task_has_users where UserId = " + userId;
var data = Database.Open("DefaultConnection").Query(sql);
List<Task_has_UsersModel> result = new List<Task_has_UsersModel>();
foreach (var item in data)
{
Task_has_UsersModel model = new Task_has_UsersModel();
model.Task_Id = Convert.ToInt32(item.Task_Id);
model.Project_Id = Convert.ToInt32(item.ProjectId);
// model.start_time = Convert.ToDateTime(item.start_time);
model.start_time = (item.start_time).ToString("yyyy-MM-dd HH-mm-ss");
model.end_time = (item.end_time).ToString("yyyy-MM-dd HH-mm-ss");
model.title = item.title;
result.Add(model);
}
return result;
}
[HttpGet]
public JsonResult GetAllEvents(string start, string end)
{
string uname = (Session["UserName"]).ToString();
var ApptListForDate = LoadAllTasks(start,end,uname);
var eventList = from e in ApptListForDate
select new
{
id=e.Task_Id,
title=e.title,
start=e.start_time,
end=e.end_time,
allDay=false,
color = "#008000",
//allDay=false,
className= "label-important" ,
};
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
finally done
Related
I want to build and return an array of objects from CloudCode based on a query and the result of a httpRequest done for each record.
The problem with the following (example) is that it adds the same value for all "element" objects for all records. From testing I know that the variables "outside" the promises.push(Parse.Cloud.httpRequest(.. (e.g. "countryName") are unique.
What am I missing here?
Thanks!
Parse.Cloud.define("search3", function(request, response) {
var rs = [];
var promises = [];
// Query CountryTemp class
var query = new Parse.Query('CountryTemp');
query.limit(1000);
query.exists("Country");
query.include("Country");
query.greaterThan('Month11', 25);
query.find().then(function(results) {
for (var i = 0; i < results.length; ++i) {
var element = {};
var result = results[i];
var country = result.get("Country");
var countryID = country.id;
var countryName = country.get("Name");
var temp = result.get("Month11");
promises.push(Parse.Cloud.httpRequest({
url: 'http://www.google.com'
}).then(function(httpResponse){
element.id = countryID;
element.countryName = countryName;
element.temp = result.get("Month11");
element.httpresponse = httpResponse.text.substr(0, 50);
rs.push(element);
}));
}
return Parse.Promise.when(promises);
}).then(function() {
response.success(rs);
}, function() {
response.error('error');
});
});
Found the problem, Using underscore "_each" instead of "for" fixed it:
var _ = require('underscore');
..
_.each(results, function(result) {
I want to Load Data and skip previous data which already append in the view using skip and take count in mvc.Here is my View where i am getting data
var skipCount = 5;
var takeCount = 5;
function loadMore() {
$(window).bind('scroll', bindScroll);
itemCount = takeCount;
skipCount += takeCount;
setTimeout(function () {
getFeed();
},100);
}
function bindScroll() {
if ($(window).scrollLeft() + $(window).width() > $('.tile-area').width() - 130) {
$(window).unbind('scroll');
loadMore();
}
}
function getFeed() {
$.ajax({
type: "Post",
url: "/PlanetFeed/PlanetfeedPartial",
dataType: "html",
data: { id: planetFeedOwnerId, filterType: filterType, taggedItemGraphId: taggedItemGraphId, itemCount: takeCount, SkipCount: skipCount }, //"feedGraphId=10696",
success: function (data) {
if (data === null) {
} else {
$('.tile-area-title').html("");
var div = $('.planetFeed:last');
div.after(data);
skipCount += takeCount + 1;
}
});
}
And Here is My Controller Where I am Passing Parameter
public ActionResult PlanetfeedPartial(Guid id, string filterType, Guid taggedItemGraphId, int itemCount, int SkipCount)
{
var planetfeedsOrder = from p in db.PlanetFeeds
where p.CurrentState != 1
join s in searchTag on p.PlanetFeedGraphId equals s.SecondaryTaggedGraphItemId
join g in db.Graphs on p.PlanetFeedItemGraphId equals g.GraphID
join u in db.UserInfos on p.PlanetFeedPosterId equals u.UserInfoID
orderby p.PostDate descending
select new PlanetFeedViewModel
{
Username = u.FirstName + " " + u.LastName,
isRootFeed = p.isRootFeed,
PostDate = p.PostDate,
CommentCount = g.CountResponses,
CountPositiveReactions = g.CountPositiveReactions,
CountNegativeReactions = g.CountNegativeReactions,
ItemID = g.ItemID,
UserLevel = u.UserLevel,
CurrentState = p.CurrentState,
Address = g.Address
};
return PartialView("_PlanetfeedPartial", planetfeedsOrder.OrderByDescending(p => p.PostDate).Skip(SkipCount).Take(itemCount).ToList());
}
I am not getting proper Data and every time when i am loading data in scroll getting different data not in a proper sequence and all data not loading
var planetfeedsOrder = (from p in db.PlanetFeeds
where p.CurrentState != 1
join s in searchTag on p.PlanetFeedGraphId equals s.SecondaryTaggedGraphItemId
join g in db.Graphs on p.PlanetFeedItemGraphId equals g.GraphID
join u in db.UserInfos on p.PlanetFeedPosterId equals u.UserInfoID
orderby p.PostDate descending
select new PlanetFeedViewModel
{
Username = u.FirstName + " " + u.LastName,
isRootFeed = p.isRootFeed,
PostDate = p.PostDate,
CommentCount = g.CountResponses,
CountPositiveReactions = g.CountPositiveReactions,
CountNegativeReactions = g.CountNegativeReactions,
ItemID = g.ItemID,
UserLevel = u.UserLevel,
CurrentState = p.CurrentState,
Address = g.Address
}).orderby(o=>o.id).skip(100);
skip One hundred then shows your data and create order by any id or string that you want sequence data.
net MVC application, in which I have multiple charts. On these charts, I have applied filters and by clicking each filter, I do an ajax call which returns the result in Json and then applies to the charts.
Now its working perfectly in Firefox and Chrome, but in Internet Explorer - Ajax call is always unsuccessful. I tried hitting the web api url directly through my browser and the issue it seems is, the result json was being returned as a file to be downloaded.
This is my ajax code :
function getIssueResolvedGraphdata(control, departCode, departName) {
$.ajax(
{
type: "GET",
url: WebApiURL + "/api/home/GetQueryIssueResolvedData?deptCode=" + departCode,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (myData) {
var resolvedStartDate = myData.data.IssueResolvedStartDate;
var issueData = myData.data.IssueData;
var resolveData = myData.data.ResolvedData;
//converting issueData into integer array...
var issue = issueData.replace("[", "");
var issue1 = issue.replace("]", "");
var issue2 = issue1.split(",");
for (var i = 0; i < issue2.length; i++) { issue2[i] = parseInt(issue2[i]); }
//converting resolvedData into integer array
var resolve = resolveData.replace("[", "");
var resolve1 = resolve.replace("]", "");
var resolve2 = resolve1.split(",");
for (var j = 0; j < resolve2.length; j++) { resolve2[j] = parseInt(resolve2[j]); }
//getting max value from array...
var issueMaxVal = Math.max.apply(null, issue2);
var resolveMaxVal = Math.max.apply(null, resolve2);
//Eliminating leading zeros in issue array
var removeIndex = 0;
var myDate;
var newDate;
var arrayLength;
if (issueMaxVal != 0) {
arrayLength = issue2.length;
for (var i = 0; i < arrayLength; i++) {
if (issue2[0] == 0) {
issue2.splice(0, 1);
removeIndex = i;
} else {
break;
}
}
//Getting days count of current month
var monthStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
var monthEnd = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1);
var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24);
var monthDays = 0;
if (monthLength == 28) {
monthDays = removeIndex;
}
else if (monthLength == 30) {
monthDays = removeIndex + 1;
}
else if (monthLength == 31 || monthLength == 29) {
monthDays = removeIndex + 2;
}
//matching the resultant issue array with resolve array & setting start date
var iDate = resolvedStartDate;
var tDate = '';
for (var i = 0; i < iDate.length; i++) {
if (iDate[i] == ',') {
tDate += '/';
}
else {
tDate += iDate[i];
}
}
if (removeIndex != 0) {
resolve2.splice(0, (removeIndex + 1));
var myDate = new Date(tDate);
myDate.setDate(myDate.getDate() + monthDays);
newDate = Date.UTC(myDate.getFullYear(), (myDate.getMonth() + 1), myDate.getDate());
} else {
var myDate = new Date(tDate);
newDate = Date.UTC(myDate.getFullYear(), (myDate.getMonth() + 1), myDate.getDate());
}
} else {
alert("Empty");
}
//updating chart here...
var chart = $('#performance-cart').highcharts();
chart.series[0].update({
pointStart: newDate,
data: issue2
});
chart.series[1].update({
pointStart: newDate,
data: resolve2
});
if (issueMaxVal > resolveMaxVal) {
chart.yAxis[0].setExtremes(0, issueMaxVal);
} else {
chart.yAxis[0].setExtremes(0, resolveMaxVal);
}
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
} });}
Code from web api controller :
[HttpGet]
[CrossDomainActionFilter]
public Response<GraphIssueResolvedWrapper> GetQueryIssueResolvedData(string deptCode)
{
Response<GraphIssueResolvedWrapper> objResponse = new Response<GraphIssueResolvedWrapper>();
GraphIssueResolvedWrapper objGraphIssueResolvedWrapper = new GraphIssueResolvedWrapper();
try
{
....code.....
objResponse.isSuccess = true;
objResponse.errorDetail = string.Empty;
objResponse.data = objGraphIssueResolvedWrapper;
}
catch (Exception ex)
{
objResponse.isSuccess = false;
objResponse.errorDetail = ex.Message.ToString();
objResponse.data = null;
}
return objResponse;
}
Reponse Class :
public class Response<T>
{
public bool isSuccess { get; set; }
public string errorDetail { get; set; }
public T data { get; set; }
}
I am stuck at this for hours now. Any help will be appreciated.
I have solved my problem by using the following code : ( I guess it needed CORS support)
function isIE() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE");
if (msie > 0)
return true;
return false;
}
Then in document.ready function of my binding script :
$(document).ready(function () {
if (isIE())
$.support.cors = true;
});
Note : it still download Json stream as a file but now my AJAX call is successful upon each hit.
You've missed contentType: 'text/html' which is pretty important for IE7-8:
$.ajax(
{
type: "GET",
url: WebApiURL + "/api/home/GetQueryIssueResolvedData?deptCode=" + departCode,
dataType: "json",
contentType: 'text/html'
crossDomain: true,
async: true,
cache: false,
success: function (myData) {
var result = JSON.parse(myData);
///...code...
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
}
}
);
To make it works in IE7-8 you also need to be sure that you've writing Conrent-Type Header into your response on server side. Add this line right before return statement;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html; charset=iso-8859-1");
And in code probably you will need to parse result in success method by using JSON.parse(myData);
i have a kendodropdown list with the workername and details... how can i fetch the ID of the selected worker so i can able to save... everytime i save it returns a null value in ID.. thanks for those who can help
Heres my code:
<input id="titles" class:"validate[required] inputLong" style="width: 400px;" />
$(document).ready(function () {
var clientCusPosId = $("#clientCusPosId").val();
$("#titles").kendoDropDownList({
dataTextField: "workerName",
dataValueField: "workerID",
autoBind: false,
// define custom template
template:
'<h5>${ data.workerName }</h5>' +
'<p>${ data.workerID }</p>' +
'<p>${ data.AvailableDay_LookID }</p>' +
'<p>${ data.StartTime } - ${ data.EndTime }</p>',
optionLabel: "Assign worker",
dataSource: {
transport: {
read: {
url: '/Client/LoadWorkerDropdownList?clientCusPosId=' + clientCusPosId,
dataType: "json",
type: "POST"
}
}
}
});
var dropdownlist = $("#titles").data("kendoDropDownList");
dropdownlist.list.width(250);
});
My Controller:
[Authorize]
[HttpPost]
public ActionResult ClientWorkerPositionSave(FormCollection formCollection)
{
String msg = String.Empty;
String clientWorkerPosId = formCollection["clientWorkerPosId"];
String clientID = formCollection["clientId"];
String clientCusId = formCollection["clientCusPosId"];
String workerID = formCollection["titles"];
Client_Worker_Position clientCusPos = new Client_Worker_Position();
try
{
if (String.IsNullOrWhiteSpace(clientWorkerPosId) || clientWorkerPosId == "0")
{
clientCusPos.ClientCustomerPositionID = Convert.ToInt32(clientCusId);
clientCusPos.WorkerID = Convert.ToInt32(workerID);
clientCusPos.ClientID = Convert.ToInt32(clientID);
clientCusPos.DateCreated = DateTime.UtcNow;
clientCusPos.DateModified = DateTime.UtcNow;
clientCusPos.CreatedBy = User.Identity.Name;
clientCusPos.ModifiedBy = User.Identity.Name;
db.Client_Worker_Position.Add(clientCusPos);
}
else
{
int id = Convert.ToInt32(clientWorkerPosId);
clientCusPos = (from a in db.Client_Worker_Position
where a.ID == id
select a).SingleOrDefault();
clientCusPos.ClientCustomerPositionID = Convert.ToInt32(clientCusId);
clientCusPos.WorkerID = Convert.ToInt32(workerID);
clientCusPos.ClientID = Convert.ToInt32(clientID);
clientCusPos.DateModified = DateTime.UtcNow;
clientCusPos.ModifiedBy = User.Identity.Name;
}
}
catch (Exception)
{
msg = "Failed to save";
}
db.SaveChanges();
if (String.IsNullOrWhiteSpace((msg)))
{ TempData["message"] = "Saved Successfully."; }
else if (msg != "")
{ TempData["message"] = msg; }
return RedirectToAction("ClientCustomerDetails", new { });
}
It could be as simple as using $("#titles).val() to get your WorkerID since it has already been configured.
Create a hidden input field hidden id="workerID" then before your post or in a drop down change event set it to $("#workerID").val($("#titles).val()). This should come across in your controller collections.
my controller action:
[HttpPost]
public ActionResult AddPointAndCopyOtherSongToPlaylist(int id)
{
if (CheckIfAddPointToSelf(User.Identity.Name, id))
{
var song = repository.GetSong(id);
foreach (var item in song.Points)
{
if (User.Identity.Name == item.UsernameGavePoint)
{
var data1 = 1;
return Json(new {data1}, JsonRequestBehavior.AllowGet);
}
}
var originalSong = repository.GetSong(id);
var newSong = new Song();
newSong.UserName = User.Identity.Name;
newSong.Title = originalSong.Title;
newSong.YoutubeLink = originalSong.YoutubeLink;
newSong.GenreId = 38;
newSong.Date = DateTime.Now;
repository.AddSong(newSong);
var point = new Point();
point.UsernameGotPoint = originalSong.UserName;
point.UsernameGavePoint = User.Identity.Name;
point.Date = DateTime.Now;
point.Score = 1;
point.OtherSongId = id;
repository.AddPoint(point);
repository.Save();
int data = 2;
//process here
return Json(new { data }, JsonRequestBehavior.AllowGet);
}
else
{
return null;
}
}
based on different scenarios I want to return a javascript and somehow notify the client of what was returned and based in the result do something in the success part of my ajax call:
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Home/AddPointAndCopyOtherSongToPlaylist/",
type: "POST",
data: { id: songId },
success: function (data,one) {
if (data && !one) {
HideAjaxLoader(), ShowMsg("Song Added Successfully");
}
else if(!data) {
HideAjaxLoader(), ShowMsg("you cannot add your own songs");
}
else if (data && one) {
HideAjaxLoader(), ShowMsg("You cannot add the same song twice");
}
},
error: function () { HideAjaxLoader(), ShowMsg("Song could not be added, please try again") }
});
});
I tried many different variations but I think i need something like data.property1 returned and in the client to check if that property exists or soemthing like that.. please help
You need to return your status code within the object.
return Json( new { data1 = "Some Other Data", status = 1} );
Then in your success handler check data.status.
if (data.status === 1) {
alert(data.data1);
}