7

I am using FullCalendar in my asp.net mvc application. It does not load events. I am getting event list by ajax call. Below is my code. What is wrong with it.?

<div class="row">
    <div class="col-lg-12">
        <section class="panel">
            <div class="panel-body">
                <div id="calendar"></div>
            </div>
        </section>
    </div>
</div>
<script type="text/javascript">
    jQuery.extend({
        getValues: function (url) {
            var result = null;
            $.ajax({
                url: url,
                type: 'get',
                dataType: 'json',
                async: false,
                success: function (data) {
                    result = data;
                },
                error: function (err) {
                    alert(JSON.stringify(err));
                }
            });
            return result;
        }
    });
    var jsonEvents = $.getValues('@Url.Action("GetEvents", "Booking")');
    alert(jsonEvents);

    //var jsonEvents = [{ title: "Dhaval, (4,6), 6", start: "05/21/2016 1:05:00 PM" },
    //    { title: "Mohit, (2), 4", start: "05/21/2016 1:05:00 PM" }]

    $('#calendar').fullCalendar({
        header:
        {
            left: 'prev,next today',
            center: 'title',
            right: 'agendaWeek,agendaDay'
        },
        allDay: true,
        defaultView: 'agendaWeek',
        events: jsonEvents//'@Url.Action("GetEvents", "Booking")'
    });
</script>

**the js in comment is just for example format. ** And the GetEvents/Controller is as below,

public Json GetEvents()
{
    string query = "query to get events";
    // columns in result table are: id, title, date
        try
        {
            SqlConnection connection = new SqlConnection("connectionString");
            connection.Open();
            SqlCommand command = new SqlCommand(query, connection);
            SqlDataReader events = command.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(events);
            string result = DataTableToJSONWithStringBuilder(dt);
            connection.Close();
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex) { }
    }
public string DataTableToJSONWithStringBuilder(DataTable table)
    {
        var JSONString = new StringBuilder();
        if (table.Rows.Count > 0)
        {
            JSONString.Append("[");
            for (int i = 0; i < table.Rows.Count; i++)
            {
                JSONString.Append("{");
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    if (j < table.Columns.Count - 1)
                    {
                        JSONString.Append(table.Columns[j].ColumnName.ToString() + ":" + "\"" + table.Rows[i][j].ToString() + "\",");
                    }
                    else if (j == table.Columns.Count - 1)
                    {
                        JSONString.Append(table.Columns[j].ColumnName.ToString() + ":" + "\"" + table.Rows[i][j].ToString() + "\"");
                    }
                }
                if (i == table.Rows.Count - 1)
                {
                    JSONString.Append("}");
                }
                else
                {
                    JSONString.Append("},");
                }
            }
            JSONString.Append("]");
        }
        return JSONString.ToString();
    }

This is the format I want. [{title:"John, (2,1), 6",start:"13/05/2016 12:00:00 AM"},{title:"Olivia, (11,4), 6",start:"11/05/2016 12:00:00 AM"}]

Getting following error when inspect element. :
Failed to load resource: the server responded with a status of 400 (Bad Request) : http: localho../ABC/[%7Btitle:%22John,%20(4,6),%206%22,start:%2205/21/2016%201:05:00%20PM%22,end:%2205/21/2016%201:30:00%20PM%22%7D,%7Btitle:%22Olivia,%20(2),%204%22,start:%2205/21/2016%201:05:00%20PM%22,end:%2205/21/2016%201:30:00%20PM%22%7D]?start=2016-05-15&end=2016-05-22&_=1463885539445

here I have commented var jsonEvents = [...]. When I use predefined events, the calendar shows them perfect. But when I call to server, there is error. DOES FULLCALENDAR ONLY SHOWS THE EVENTS FROM A FILE STORED ON THE SERVER. BECAUSE THE DOCUMENTATION SHOWS ONLY URL TO A FILE THAT CONTAINS JSON DATA.

Help me. Thanks.

DhavalR
  • 1,409
  • 3
  • 29
  • 57

3 Answers3

5

Your only true problem that makes your calendar not to show up is:

defaultView: 'agendaweek',

It has to be

 defaultView: 'agendaWeek',

Yes... Capital letter messed up your hole thing.

And you don't need all the other

$("#calendar").fullCalendar(...)

beside your main one. keep only this (with Capital W)

$('#calendar').fullCalendar(
            {
                header:
                {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay'
                },
                defaultView: 'agendaWeek',
                selectable: false,
                selectHelper: false,
                events: events
            });

EDIT

That's because your date format is incorrect. The default is MM/dd/YYYY. you're trying to set a date to month 13. And the reason you have multiple calendars is that you set it multiple times. Just do it once. You can see a working example here with your json (I Corrected the dates). Just clean all your javascript and HTML to be like in the jsFiddle example and then start add things of your own.

Eyal Abir
  • 1,080
  • 8
  • 11
  • change to `agendaWeek` shows two calendars overlapping. so I changed to `basic`, both cases does not load events. – DhavalR May 20 '16 at 14:12
  • What `jquery` version you added.? – DhavalR May 21 '16 at 12:19
  • In the fiddle it is 2.2.1 but I checked it with 1.7.2 and it also works. try to add also moment.js and make sure it's loaded before the calendar.js - https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js – Eyal Abir May 21 '16 at 13:30
  • see the edited code. it works perfect, but when fetching data from controller, same error; does not on the calendar. – DhavalR May 21 '16 at 21:24
  • Not sure I got which error still happening. The fcViews... Or the error 400? Or both of them? The error 400 happened before also? – Eyal Abir May 22 '16 at 03:47
  • 400. When I try to get records from controller. – DhavalR May 22 '16 at 03:52
  • 400 means that the URL you try to reach is incorrect. Try to console. Log the @Url.Action(... What is the result? – Eyal Abir May 22 '16 at 03:58
  • I tried to debug setting breakpoint. It is redirecting perfectly. See the code. There is a line `alert (jsonEvenys)`. It gives exect result I want. – DhavalR May 22 '16 at 04:00
  • Can you please edit your question to tell which code parts are relevant now? There are 2 js sample codes. – Eyal Abir May 22 '16 at 04:06
  • Js in comment is just for example format. The part of jquery.extend and jasonEvents=url should be considered now. – DhavalR May 22 '16 at 04:10
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/112599/discussion-between-eyal-abir-and-dhavalr). – Eyal Abir May 22 '16 at 04:12
  • Hi, lost you on the chat, It is not a file. the *.php is a server controller just like yours. all you need to do is return a json string from your controller. Did the 400 error solved by changing from POST to GET? – Eyal Abir May 22 '16 at 06:03
2

try below code:

$(document).ready(function () {

    var sourceFullView = { url: '/Booking/GetEvents/' };
    var CalLoading = true;

    $('#calendar').fullCalendar({
        header: {
            left: '',
            right: '',
            center: 'prev,title,next',
        },
        defaultView: 'month',
        editable: true,
        allDaySlot: false,
        selectable: true,
        slotMinutes: 15,
        droppable: true,
        events: '/Booking/GetEvents/'
    });
});

I am not sure about what you are getting in JSON response from your query there. so if you could try of fetching records by using Entity Framework Linq query then, below is my sample code that might help you.

public JsonResult GetEvents()
{
    try
    {
        var eventsList = from ev in db.YourTableName
        select new
        {
            Id = ev.Id,
            Title = ev.Title,
            Date = ev.Date
        };
        var rows = eventsList.ToArray();
        return Json(rows, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
Kablam
  • 2,494
  • 5
  • 26
  • 47
  • What should I do with `ColLoading`.? And I am getting events in `JsonResult`, but just don't load on the calendar. It shows the error I provided. – DhavalR May 20 '16 at 18:17
  • you need to remove $.ajax(); code, that is not required as we provided. "events: '/Booking/GetEvents/'" into calendar. and it will be calling that method. please cut your calendar control from $.Ajax() method and keep it in $(document).ready(function () { }; you can remove var sourceFullView = { url: '/Booking/GetEvents/' }; var CalLoading = true; both these lines – Jignesh Jinjariya May 20 '16 at 19:05
  • see the edit. and removing `ajax` function does not call `GetEvents` method. I tried `/Booking/GetEvents/` and `@Url.Action("","")` in `document.ready...` – DhavalR May 21 '16 at 01:29
2

try

events: { url: '@Url.Action("GetEvents", "Booking")', type:'GET', ..}

instead of

events :'@Url.Action("GetEvents", "Booking")'

Click Here for full reference of Event Object Properties.

bharat parmar
  • 302
  • 3
  • 14
sucil
  • 116
  • 2
  • 7