FullCalendar events not showing when from JSON feed - c#

I have this FullCalendar portion of code on my page to pull events from an API controller in a Razor Pages project:
var calendar;
document.addEventListener('DOMContentLoaded', function () {
var calendarEl = document.getElementById('calendar');
calendar = new FullCalendar.Calendar(calendarEl, {
plugins: ['dayGrid', 'interaction', 'list', 'timeGrid'],
defaultView: 'dayGridMonth',
customButtons: {
newEventButton: {
text: 'new event',
click: function () {
window.location.assign("Calendars/EditPersonnelEvent/0");
}
}
},
header: {
left: 'prev,next today',
center: 'title',
right: 'newEventButton,dayGridMonth,timeGridWeek,timeGridDay'
},
events: "/api/fetchEvents"
});
calendar.render();
})
and it seems to be working just fine, here's the snip of the fetch:
The problem is, the event fetched doesn't show on the calendar, on any of the views. When I paste that JSON into a hard-coded event, it works fine and I see the event, just not when it's from the GET. I've tried this with eventSources to no avail. I've searched about 30 different answers here and still no luck. The JSON seems to be formatted correctly, it seems to be getting fetched correctly, it's just not showing up. And yes, I'm looking at the correct days ;)
REQUESTED UPDATE:
Here is the "response" data:
and here's the .NET code for this fetch:
[Route("api/fetchEvents")]
[ApiController]
public class FetchEventsController : ControllerBase
{
private readonly IPersonnelEventService _personnelEventService;
public FetchEventsController(IPersonnelEventService personnelEventService)
{
_personnelEventService = personnelEventService;
}
// GET: api/FetchEvents/5
[HttpGet]
public string Get(string start, string end)
{
int currentUserId = User.Identity.GetUserId();
DateTime objStart = DateTime.Parse(start, null, System.Globalization.DateTimeStyles.RoundtripKind);
DateTime objEnd = DateTime.Parse(end, null, System.Globalization.DateTimeStyles.RoundtripKind);
List<Entities.PersonnelEvent> events = new List<Entities.PersonnelEvent>(_personnelEventService.GetPersonnelEventsByUserId(currentUserId, objStart, objEnd));
return JsonConvert.SerializeObject(events.Select(pe => pe.GetEventAsFullCalendarJson()).ToList());
}
}
and here's the code for "GetEventAsFullCalendarJson":
public string GetEventAsFullCalendarJson()
{
var info = new
{
title = Name,
start = StartDate,
end = EndDate
};
return JsonConvert.SerializeObject(info);
}
}

The problem is you are double-serializing your data.
You serialise each event object individually in GetEventAsFullCalendarJson() when you do return JsonConvert.SerializeObject(info);. So at that point you already have a JSON string representing a single event.
But then you combine all these together and serialise the whole thing again when you write return JsonConvert.SerializeObject(events.Select(pe => pe.GetEventAsFullCalendarJson()).ToList()); in the Get() method. This means the already-serialised JSON event strings are serialised again - which is why you've got quote marks round the event object (e.g. "{ ... }" and then escaped quotemarks (\") within it.
The outcome is that to fullCalendar, your data just looks like an array of strings, not an array of event objects.
The fix is simple - remove the serialisation of the individual events. An object/array must be serialised all at once to create a coherent single piece of JSON.
This:
return JsonConvert.SerializeObject(events.Select(pe => {
title = pe.Name,
start = pe.StartDate,
end = pe.EndDate
}).ToList());
would work, I think.

Related

Angular/C# null body sent for POST

I've trying to do a POST in Angular, which makes a call to my C# backend. One API call works fine, but the other one doesn't exactly. I'm having a hard time figuring out what's going on, but I see that when I open the Network window in my browser's DevTools, the request payload has the JSON populated just fine. But in C#/the backend, it receives a null object, and I get a 200 code/null response from the call.
I've got the following code in Angular:
item.service.ts
private readonly _api = '...'
private postOptions = { headers: { 'Content-Type': 'application/json; charset=utf-8' }};
public addItem(formGroup: formGroup, isInactive: boolean): Observable<Item> {
let api = ``;
// These require different API calls depending on the flag
if (isInactive)
api = `${this._api}/AddInactiveItem`;
else
api = `${this._api}/AddItem`; // This one is the one having issues
const body = ItemPost.parse(formGroup.value);
return this.http.post<Item>(api, body, this.postOptions).pipe(
this.handle(
"POST successful",
"Error with POST"
)
);
}
item-post.ts
export class ItemPost {
Name: string;
Inactive: string;
...
public static parse(obj: any): ItemPost {
return !obj ? undefined : {
Name: obj.name,
Inactive: obj.inactive,
...
};
}
}
My backend/POST code is in C#. Both of my POST methods are built the exact same, but with different SQL calls.
[HttpPost]
public JsonResult AddInactiveItem([FromBody] ItemBody item)
{
if (!ModelState.IsValid)
return Json(null);
// Do SQL call for POST here, return JSON
}
[HttpPost]
public JsonResult AddItem([FromBody] ItemBody item) // This is where I have a breakpoint and it's passing in null
{
if (!ModelState.IsValid)
return Json(null); // And this is where I find myself
// Do SQL call for POST here, return JSON
}
JSON Payload (sorry, unable to get a screenshot but this is what I'm seeing):
{"Name":"Test", ..., "Inactive":"N"}
I think you are having problem with:
`$(this.api}/AddInactiveItem`
The right syntax for template strings is:
`${this.api}/AddInactiveItem`
I figured it out...and I feel dumb. Really dumb.
An int variable in Item was considered an optional int/number in the front-end for when an Item was considered active (not inactive), but in the backend, ItemBody didn't reflect that and was considered as just an int instead of int?. I had to dig through my ModelState errors through the debugger and it hinted this, but it's late at night and my mind didn't process it.
Gotta make sure all of the variable types are reflected properly in the Body object.

Uncaught (in promise) TypeError: data.map is not a function (React using axios getting data from ASP.NET API)

I've created an API using ASP.NET, and I've got a Website running React. I'm wanting to display the data retrieve with a get request from the API to React using Axios. The website has an authentication method using two cookies. I can get the Axios to get data from https://jsonplaceholder.typicode.com/users, but when i use the same bit of code, then I get the error: Uncaught (in promise) TypeError: data.map is not a function.
I've tried as mentioned above to use a placeholder, and that works fine, but can't seem to get thedata from my API, which leads me to believe that the problem lies in the cookies. I've also tried a few Google searches, which returned that I should include withCredentials: true, but that doesn't do the trick.
Here is the function from my API:
public JsonResult YearlyManagersJSON(int year = 0)
{
if (year < 2000 || year > DateTime.Today.Year)
year = DateTime.Today.Year;
var startDate = new DateTime(year, 1, 1);
var endDate = new DateTime(year + 1, 1, 1);
var bonds = this.getOverviewData(ReportType.BONDS, startDate, endDate);
var bondsSum = bonds.Sum(m => m.Aggregate);
var viewData = new TopLeadManagerViewData
{
Title = String.Format("Top Managers in {0}", startDate.Year),
Currency = SiteHelper.getCurrencyToUse(),
Bonds = Enumerable.Select(bonds, m => new ManagerSummary()
{
NumberOfIssues = (int)m.Aggregate2,
TotalAmount = m.Aggregate * 1000000,
Name = m.Group.ToString(),
Share = 100.0m * m.Aggregate / bondsSum
}),
};
return this.Json(viewData, JsonRequestBehavior.AllowGet);
}
This returns a JSON, which i have checked using Postman. Then i try to access the data using axios.
state = {
yearlyBonds: []
}
componentDidMount() {
axios.get(
'http://localhost/Stamdata.Web/LeagueTable/YearlyManagersJSON',
{ withCredentials: true }
)
.then(res => {
const yearlyBonds = res.data;
this.setState({ yearlyBonds });
})
}
render() {
return (
// Tags removed for simplicity
<ListTable data={this.state.yearlyBonds.Bonds} />
The data is then passed down into the component
function ListTable(props) {
const { classes, header, data } = props;
return(
// Tags removed for simplicity
<TableBody>
{data.map((x, i) => {
return(
<TableRow key={i}>
<TableCell scope="row">{x.Name}</TableCell>
<TableCell scope="row">{x.TotalAmount}</TableCell>
<TableCell scope="row">{x.Share}</TableCell>
<TableCell scope="row">{x.NumberOfIssues}</TableCell>
</TableRow>
)
})}
</TableBody>
So, this returns the error
"Uncaught (in promise) TypeError: data.map is not a function", which I would like to have display the data retrieved.
Your initial state is,
yearlyBonds: []
When component first renders it takes initial state. Initially you have empty array. So iteration over empty array giving you the error.
You can conditionally add your component like,
{ this.state.yearlyBonds.Bonds && <ListTable data={this.state.yearlyBonds.Bonds} />}
Note that, componentDidMount gets called after 1st render (when component mounts into DOM).
You have following workflow for the component -
During the 1st render, you have a state -
state = {
yearlyBonds: []
}
In the render function, you want to pass Bonds key data which doesn't exist in your initial state until API call is made and state has Bonds data.
Since this.state.yearlyBonds.Bonds is undefined during initial render, you can't call map method on undefined object. That is why you're seeing that error.
Now to fix this, there are quite a few methods:
Method #1 (Simplest):
Update your state like this -
state = {
yearlyBonds: {
bonds: []
}
}
Your render would work without any additional changes.
Method #2 (Moderate):
Update your function to accept de-structured props with default value for data
function ListTable({ classes, header, data=[] }) {
// rest of the code goes here
Method #3: (The right approach for API calls):
Add a isLoading flag in your component state. We will use this to show a fallback 'Loading ...' UI until we have data from the API.
state = {
yearlyBonds: [],
isLoading: false,
}
Before API call is made, update your state with 'isLoading' set to true.
componentDidMount() {
// update state
this.setState({ isLoading: true });
axios.get(
'http://localhost/Stamdata.Web/LeagueTable/YearlyManagersJSON',
{ withCredentials: true }
)
.then(res => {
const yearlyBonds = res.data;
// set isLoading to false, as data is received
this.setState({ yearlyBonds, isLoading: false });
})
}
Finally in the render method, read isLoading state and render a fallback.
// rest of the code
render() {
if (this.state.isLoading) {
return <div> Loading ... </div>;
// when data is available
return (
// Tags removed for simplicity
<ListTable data={this.state.yearlyBonds.Bonds} />
It happens because you are iterating over an empty array.

Jquery Post to ASP.NET API Controller

I have a form that is generated via jquery:
$.get("/api/get/getListItems", function (data) {
var table = "";
table += "<table>";
$.each(data, function (y, z) {
console.log(z);
table += '<tr>';
$.each(this, function (k, v) {
table += '<td><input type="text" name="' + k + '" id="' + k + '" value="' + v + '" /></td>';
});
table += '<td><input type="checkbox" name="selected" id="selected" /></td>';
table += '</tr>';
});
table += '<tr><td><input type="submit" id="submit" name="submit" value="Save To Database" /></td></tr>';
table += '</table>';
$('#form').html(table);
});
and it generates this HTML (10 rows of input fields, 7 columns and 1 checkbox): http://jsfiddle.net/8zpr2fkL/1/
and I am submitting the form when the submit button is clicked:
$("#form").submit(function (event) {
$.post("/api/update/", $("#form").serialize(), alert('success'));
});
Now I am passing the data to my ASP.NET API Controller:
[HttpPost]
public dynamic Post([FromBody]CellModel cells)
{
UpdateClass jobs = new UpdateClass();
return jobs;
}
and here is my CellModel class:
public class CellModel
{
public uint scheduleTaskID { get; set; }
public string task { get; set; }
public string baselineDate { get; set; }
public string scheduledDate { get; set; }
public string actualDate { get; set; }
public string finishedDate { get; set; }
public bool selected { get; set; }
public override string ToString()
{
return scheduleTaskID.ToString();
}
}
My Problem is when I hit submit to submit the data and put a breakpoint on the controller method, cells count is 0, is there something I am missing here? I am trying to pass all the data in the input text to controller. Nothing is getting passed to my controller. What am I doing wrong?
This is data im trying to pass via jquery $('#form').serialize():
scheduleTaskID=194&task=Permit&baselineDate=6%2F23%2F2005+8%3A00%3A00+AM&scheduledDate=6%2F23%2F2005+8%3A00%3A00+AM&actualDate=6%2F23%2F2005+8%3A00%3A00+AM&finishedDate=&scheduleTaskID=195&task=Office+Files&baselineDate=7%2F13%2F2005+8%3A00%3A00+AM&scheduledDate=7%2F13%2F2005+8%3A00%3A00+AM&actualDate=7%2F13%2F2005+8%3A00%3A00+AM&finishedDate=&scheduleTaskID=196&task=Foundation&baselineDate=7%2F27%2F2005+8%3A00%3A00+AM&scheduledDate=7%2F27%2F2005+8%3A00%3A00+AM&actualDate=8%2F13%2F2005+8%3A00%3A00+AM&finishedDate=&scheduleTaskID=197&task=Framing&baselineDate=8%2F5%2F2005+8%3A00%3A00+AM&scheduledDate=8%2F5%2F2005+8%3A00%3A00+AM&actualDate=8%2F23%2F2005+8%3A00%3A00+AM&finishedDate=&scheduleTaskID=198&task=Finishes+Exterior&baselineDate=8%2F26%2F2005+8%3A00%3A00+AM&scheduledDate=8%2F26%2F2005+8%3A00%3A00+AM&actualDate=9%2F14%2F2005+8%3A00%3A00+AM&finishedDate=&scheduleTaskID=199&task=Drywall&baselineDate=9%2F2%2F2005+8%3A00%3A00+AM&scheduledDate=9%2F2%2F2005+8%3A00%3A00+AM&actualDate=9%2F16%2F2005+8%3A00%3A00+AM&finishedDate=&scheduleTaskID=200&task=Flooring&baselineDate=9%2F1%2F2005+8%3A00%3A00+AM&scheduledDate=9%2F1%2F2005+8%3A00%3A00+AM&actualDate=9%2F20%2F2005+8%3A00%3A00+AM&finishedDate=&scheduleTaskID=201&task=General+Finish&baselineDate=9%2F12%2F2005+8%3A00%3A00+AM&scheduledDate=9%2F12%2F2005+8%3A00%3A00+AM&actualDate=&finishedDate=&scheduleTaskID=202&task=Final+PDI&baselineDate=10%2F11%2F2005+8%3A00%3A00+AM&scheduledDate=10%2F11%2F2005+8%3A00%3A00+AM&actualDate=&finishedDate=&scheduleTaskID=203&task=Permit&baselineDate=4%2F6%2F2005+8%3A00%3A00+AM&scheduledDate=4%2F6%2F2005+8%3A00%3A00+AM&actualDate=4%2F6%2F2005+8%3A00%3A00+AM&finishedDate=
UPDATE
I have changed:
$("#form").submit(function (event) {
$.post("/api/update/", $("#form").serialize(), alert('success'));
});
to
$("#form").submit(function (event) {
var array = [];
$('#form > table > tbody > tr').each(function (elem) {
var item = {};
item.scheduleTaskID = $(this).find("td > #scheduleTaskID").val();
item.task = $(this).find("td > #task").val();
item.baselineDate = $(this).find("td > #baselineDate").val();
item.scheduledDate = $(this).find("td > #scheduledDate").val();
item.actualDate = $(this).find("td > #actualDate").val();
item.finishedDate = $(this).find("td > #finishedDate").val();
item.selected = $(this).find("td > #selected").val();
array.push(item);
});
console.log(JSON.stringify(array));
$.post("/api/update/", JSON.stringify(array), alert('success'), 'json');
});
in my console log my data looks like this:
[{"scheduleTaskID":"203","task":"Permit","baselineDate":"4/6/2005 8:00:00 AM","scheduledDate":"4/6/2005 8:00:00 AM","actualDate":"4/6/2005 8:00:00 AM","finishedDate":"","selected":"on"},{"scheduleTaskID":"195","task":"Office Files","baselineDate":"7/13/2005 8:00:00 AM","scheduledDate":"7/13/2005 8:00:00 AM","actualDate":"7/13/2005 8:00:00 AM","finishedDate":"","selected":"on"},{"scheduleTaskID":"196","task":"Foundation","baselineDate":"7/27/2005 8:00:00 AM","scheduledDate":"7/27/2005 8:00:00 AM","actualDate":"8/13/2005 8:00:00 AM","finishedDate":"","selected":"on"},{"scheduleTaskID":"197","task":"Framing","baselineDate":"8/5/2005 8:00:00 AM","scheduledDate":"8/5/2005 8:00:00 AM","actualDate":"8/23/2005 8:00:00 AM","finishedDate":"","selected":"on"},{"scheduleTaskID":"198","task":"Finishes Exterior","baselineDate":"8/26/2005 8:00:00 AM","scheduledDate":"8/26/2005 8:00:00 AM","actualDate":"9/14/2005 8:00:00 AM","finishedDate":"","selected":"on"},{"scheduleTaskID":"199","task":"Drywall","baselineDate":"9/2/2005 8:00:00 AM","scheduledDate":"9/2/2005 8:00:00 AM","actualDate":"9/16/2005 8:00:00 AM","finishedDate":"","selected":"on"},{"scheduleTaskID":"200","task":"Flooring","baselineDate":"9/1/2005 8:00:00 AM","scheduledDate":"9/1/2005 8:00:00 AM","actualDate":"9/20/2005 8:00:00 AM","finishedDate":"","selected":"on"},{"scheduleTaskID":"201","task":"General Finish","baselineDate":"9/12/2005 8:00:00 AM","scheduledDate":"9/12/2005 8:00:00 AM","actualDate":"","finishedDate":"","selected":"on"},{"scheduleTaskID":"202","task":"Final PDI","baselineDate":"10/11/2005 8:00:00 AM","scheduledDate":"10/11/2005 8:00:00 AM","actualDate":"","finishedDate":"","selected":"on"},{"scheduleTaskID":"203","task":"Permit","baselineDate":"4/6/2005 8:00:00 AM","scheduledDate":"4/6/2005 8:00:00 AM","actualDate":"4/6/2005 8:00:00 AM","finishedDate":"","selected":"on"},{}]
and in my ASP.NET API Controller, I changed my method to this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class UpdateController : ApiController
{
[HttpPost]
public dynamic Post(List<CellModel> cells)
{
UpdateClass jobs = new UpdateClass();
//jobs.PostScheduledTasks(cells);
return cells;
}
}
}
I put a breakpoint at the start of the method Post and when it hits the breakpoint, it says cells Count = 0..I see network call, only if i put a return false after my post call and the response is empty [] Why is the data not passing to my controller, is it because the form is being generated by jquery?
UPDATE
Still no solution, I looked at my network call this AM and the Status Code is 301:
Don't use $.post
use ajax post and set the content type to
"application/json; charset=utf-8"
var data = JSON.stringify(array);
$.ajax({
url:"/api/update/",
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data){
console.log(data);
}
});
the problem is that you need to say to the webserver you are sending json and is not possible with $.post
This is really normal, and I have been struggling with this too (and sometimes I still forget), here you can see that you have to use $.ajax
Jquery - How to make $.post() use contentType=application/json?
While you got an alternative approach by #dariogriffo, i want to give you a full solution using your initial approach with $.post.
Your initial approach with form serialization was correct, so the following code is correct:
$("#form").submit(function (event) {
$.post("/api/update/", $("#form").serialize(), alert('success'));
});
However, this wasn't working because your dynamic form is not following the naming conventions for input fields expected by the ASP.NET MVC Default model binder, and as a consequence your serialized form was not something the default model binder was capable of binding to your cells model. That is why you were not getting any cells in the controller when doing a POST.
To clarify what that means, ASP.NET expects each input field that corresponds to a model property to have the following name format if you are posting to a regular MVC 5 Controller:
actionattributename[index].propertyname
If you are posting to a Web API 2 controller it should be:
[index].propertyname
Since your action attribute is named cells and it has a property scheduledTaskID, and you are posting to a WebAPI controller one of your inputs would look like:
<input type="text" name="[0].scheduleTaskID" id="scheduleTaskID" value="194">
There are a couple more rules involved in structuring a form to make it bindable. You can find a nice blog post about it here:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/
If you followed that form convention you would be able to Post your serialized form to your controller expecting a List<CellModel> cells without having to use the JSON approach, which is much more expensive as suggested in the other answers.
Below is a fiddle with an example form structured correctly by Web API 2 default binder rules:
http://jsfiddle.net/8zpr2fkL/12/
You can try to $.post this form using $.post to your web api controller and it should work like a charm!
I know, this is already solved using .ajax instead of .post. I thought of sharing this , as i have solved this using .post. As mentioned above, since it posts with content type Content-Type:application/x-www-form-urlencoded; charset=UTF-8, parameter cells in post method will contain count = 0.
To solve this, you have to manually capture request object and get post data and then do deserialize and get object as List<CellModel>. I have used all posted code by OP, and just modified post method as shown in following, and it worked.
[HttpPost]
public dynamic Post(List<CellModel> cells)
{
string content = string.Empty;
if (HttpContext.Current.Request.InputStream.CanSeek)
{
HttpContext.Current.Request.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
}
using (System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream))
{
content = reader.ReadToEnd();
}
if (!string.IsNullOrEmpty(content))
{
// Deserialize and operate over cells.
try
{
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(content, typeof(List<CellModel>));
}
catch (Exception ex)
{
return ex;
}
}
return cells;
}
Here is what i get while debugging.

Accessing C# variable from Javascript in asp.net mvc application

I have a problem in How to use javascript variables in C# and vise versa : I have this Model passing to the view:
public List<Tache> Get_List_Tache()
{
Equipe _equipe = new Equipe();
List<Tache> liste_initiale = _equipe.Get_List_tache();
return liste_initiale;
}
It's a list of objects Tache in which I'd like to use it's three fields Tache_description, Begin_date and End_date.
In my JavaScript code I have this function and it works fine:
<script>
$(document).ready(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
theme: true,
header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},
editable: true,
events: [
#foreach (var m in Model.Get_List_Tache())
{
#:{title : #m.Tache_description , start: #m.Begin_date , end : #m.Begin_date }
}
]
});
});
</script>
The values of the array events are just for test, and I need to fill events by the value of the Model. For each element like this: title = Tache_description, start = Begin_date and end = End_date.
So how can I do this task? Any suggestions?
Try this,
foreach (var item in YourList)
{
events: [{ title: '#item.title', start: '#item.start', end: '#item.end'}]
}
So, in this code just replace name your model entity.
Make a foreach razor loop within javascript :
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
theme: true,
header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},
editable: true,
events: [
#
{
bool isFirst = true;
}
#foreach(var m in Model)
{
if(!isFirst)
{
#:,
}
#:{title: #m.Tache_description, ...<other properties here>}
isFirst = false;
}
]
});
For title, you can do title = "#Tache_description"
Not sure about the format/type of your Begin_date and End_date, you may need some function to read the date into a javascript format. Shouldnt be that hard.
Loop through each element and add the elements to the events array. It is something like...
events = new Array()
#foreach(tache in list){
item = { blah : blah, blah : blah };
events.push(item);
}
for each c# item in this c# list, write these lines of javascript. You may end up with a very long javascript code block, but it should do the trick. Above is pseudocode.
To add to Darin's answer: If you need the server-side variables in an external JavaScript file, take a look this blog post: Generating External JavaScript Files Using Partial Razor Views
1: if your model is expecting the list of Tache then you have the whole list you can manipulate.
2: you can get the data using jquery ajax as json data by calling your action Get_List_Tache().
Assuming this javascript is inline in your page you could do the following:
#model IList<Tache>
<script type="text/javascript">
var events = #Html.Raw(Json.Encode(Model.Select(x => new { title = x.Description, start = x.Begin.ToString("o"), end = x.End.ToString("o") })));
$('#calendar').fullCalendar({
theme: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: events
});
</script>
This example assumes that your Tache model has properties Description, Begin and End:
public class Tache
{
public string Description { get; set; }
public DateTime Begin { get; set; }
public DateTime End { get; set; }
}
And if this script is in a separate javascript file you could still set a global events variable in your view which will later be used by your script. Alternatively you could fetch this model using an AJAX call.

jQuery select2 with remote data and asp.net

I am using select2 library for replacing select boxes. I rearranged example 7 that you can find on Select2 library page (scroll down with id
$("#e7").select2 etc...). I made my own generic handler that return serialized json data:
GetData.asxh view :
public class GetData : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public class RecipesList
{
public int total { get; set; }
public List<TopRecipeTable> recipes { get; set; }
public RecipesList() { }
public RecipesList(int total, List<TopRecipeTable> recipes)
{
this.total = total;
this.recipes = recipes;
}
}
private string GenerateJsonSerializedObject(int languageId, string orderBy)
{
RecipesList recipeList = new RecipesList(15, DBDataBase.GetTopRecipesByNumberOfRecipes(languageId, 15));
return new JavaScriptSerializer().Serialize(recipeList);
}
public void ProcessRequest(HttpContext context)
{
int languageId;
bool languageParsed = int.TryParse(context.Request["languageId"], out languageId);
string orderBy = (string)context.Request["orderBy"];
if (languageParsed && orderBy != string.Empty)
{enter code here
context.Response.ContentType = "application/json";
var jsonValue = GenerateJsonSerializedObject(languageId, orderBy);
context.Response.Write(jsonValue);
}
}
This generic handler returns the right format of json (I checked it with this URL ). My result (json) is also the same as the one in example on above mentioned page. But after this jquery doesn`t fire anymore.
My script :
$(document).ready(function () {
$("#e8").select2({
placeholder: "Search for a recipe",
//minimumInputLength: 1,
ajax: {
url: "/Handlers/GetData.ashx",
dataType: 'jsonp',
data: function (term, page) {
return {
languageId: 1,
orderBy: "TA"
};
},
results: function (data, page) {
alert(data.total);
var more = (page * 10) < data.total; // whether or not there are more results available
// notice we return the value of more so Select2 knows if more results can be loaded
return { results: data.recipes, more: more };
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection, // omitted for brevity, see the source of this page
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});
});
I tried to write the same alert(data.total) in the original example and it worked but not in my version. So I have the right json format, the jquery calls my generic handler and also recieved parameters languageId ... and also return the right json format but than nothing. I don't know if I am missing something here, because I am sure that this thing could also work with a generic handler as well. I hope I gave enough information about my problem.
I can also add my result in jquery .ajax error handler :
xhr.status = 200
ajaxOptions = parsererror
horwnError = SyntaxError : invalid label
If this is any helpful information
This question is quite old, so pretty sure you have a solution by now...but:
Remove all of these functions:
formatResult: movieFormatResult
formatSelection: movieFormatSelection
dropdownCssClass: ...
escapeMarkup:....
You did not provide those functions to format your data did you? All of those are only needed if you are making a custom drop down of items.
You are returning data.recipes - that needs to be an array of {Text:"", Id:""} or you need to build it from what you return right there.
First, get it working with just a very basic list with very basic data...then go from there.
Additionally, when you get that working try using WebApi or ServiceStack to handle your data instead of an IHttpHandler.

Categories

Resources