Event Calendar for ASP.NET MVC with dhtmlxScheduler

| Comments (109)

NOTE: We’re now offering DHTMLX Scheduler .NET, an optimized version for ASP.NET apps.

This tutorial will lead you through the steps required to integrate dhtmlxScheduler into an ASP.NET MVC application. dhtmlxScheduler is a JavaScript event calendar component, which can be used for a wide variety of use-cases connected to scheduling tasks. We will learn how to put this Ajax-based event calendar on a web page, load events from .NET sever side and update them in the database when a user makes changes in the browser.

Download the final demo to get a better understanding of the solution we’re about to build.

dhtmlxScheduler - Week View

dhtmlxScheduler - Basic Week View

Modern web apps impose ever higher demands on the user interface. In the case of standard controls, you can always use a built-in solution. However, with more complex controls – a calendar UI, for example – you are up against the problem. But here, third-party solutions can help. One of them is dhtmlxScheduler.

Preparation

First of all, you need to create a new project. Nothing specific, just an empty ASP.NET MVC project. Name it, for example, “My Calendar”. After that, create a database (or use any valid one) where you will save the calendar events. In the database, create the table “Events” with the following set of fields (all fields are mandatory):

Field Type Description
id identity, primary key the ID of an event
text text the description of an event
start_date datetime the date and the time of an event start
end_date datetime the date and the time of an event end

 
While the DB tool is open, you can add some test data to the “Events” table. If you downloaded the final demo package, you can find there MyCalendar.mdf file which already contains the necessary table and data.

The next thing you need is the dhtmlxScheduler package, which can be downloaded from the dhtmlxScheduler homepage. Copy the content from the folder ‘codebase’ to the folder ‘Scripts’ of your project. The result of this step should look similar to the following:

dhtmlxScheduler Files

dhtmlxScheduler Files

Now that everything is ready, and all the necessary files are in place, you can proceed to the first step.

Step 1 – Initialization

First of all, you need to create a default view. Add a new controller – “CalendarController” – and create the “Index” view for it. Here is the content of Index.aspx file:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
<script src="/Scripts/dhtmlxscheduler.js" type="text/javascript"></script>
<link href="/Scripts/dhtmlxscheduler.css" rel="stylesheet" type="text/css" />
<style type="text/css">
html, body
{
height:100%;
padding:0px;
margin:0px;
}
</style>
<script type="text/javascript">
function init() {
scheduler.init("scheduler_here",new Date(2010,6,1),"month");
}
</script>
</head>
<body onload="init()">
<div id="scheduler_here" class="dhx_cal_container" style='width:100%; height:100%;'>
<div class="dhx_cal_navline">
<div class="dhx_cal_prev_button">&nbsp;</div>
<div class="dhx_cal_next_button">&nbsp;</div>
<div class="dhx_cal_today_button"></div>
<div class="dhx_cal_date"></div>
<div class="dhx_cal_tab" name="day_tab" style="right:204px;"></div>
<div class="dhx_cal_tab" name="week_tab" style="right:140px;"></div>
<div class="dhx_cal_tab" name="month_tab" style="right:76px;"></div>
</div>
<div class="dhx_cal_header">
</div>
<div class="dhx_cal_data">
</div>
</div>
</body>
</html>

The default view loads .js and .css files of the dhtmlxScheduler and initializes a full-screen scheduler. The second and third parameters in the ‘scheduler.init’ command define default date and mode, which will be in the calendar just after initialization. Except for the first line, the code doesn’t have anything .NET MVC-specific. Actually, it’s fully taken from a standard scheduler example.

Now one more thing needs to be done – the updating of a default route. Switch the default route of the app to the newly-created controller in Global.asax.cs:

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Calendar", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}

When all this is done and correct, you can run the app and see the next screen:

Scheduler on page

Scheduler on page

If you don’t see the screen above, most probably you didn’t copy the scheduler’s files to the folder ‘Scripts’ correctly, so check it again.

The calendar created with the dhtmlxScheduler has a clean and intuitive interface, and managing events is quite easy. To create new events, use the double click or click-and-drag commands. By clicking on tabs in the upper right-hand corner you can switch views: Day, Week, or Month.

Step 2 – Loading Data

The view we constructed in the previous step looks fine, but it doesn’t contain any data, so now let’s change this. First, add ‘Model’ to your application (just use “Model > Add > Add new item” and select “Data”,”Linq to SQL Classes”). To complete the process, drag-and-drop the “Events” table to the Model Designer, and then add one more action to the CalendarController.cs:

public ActionResult Data()
{
MyEventsDataContext data = new MyEventsDataContext();
return View(data.Events);
}

Define view for that action – Data.aspx:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" ContentType="text/xml" %>
<data>
<% foreach (var myevent in Model) { %>
<event id="<%=myevent.id%>">
<start_date><![CDATA[<%= String.Format("{0:MM/dd/yyyy HH:mm}",myevent.start_date) %>]]></start_date>
<end_date><![CDATA[<%= String.Format("{0:MM/dd/yyyy HH:mm}",myevent.end_date) %>]]></end_date>
<text><![CDATA[<%= myevent.text%>]]></text>
</event>
<% } %>
</data>

This template outputs not HTML, but XML data. For each event it will output a block of XML data. An extra bit of code is used to provide data in the necessary format. If you need to add extra fields to the model, just add extra tags to the view.

Slightly adjust the initialization code of your scheduler in Index.aspx:

<script type="text/javascript">
function init() {
scheduler.config.xml_date = "%m/%d/%Y %H:%i"; // format of dates in XML
scheduler.init("scheduler_here", new Date(2010, 6, 1), "month");
scheduler.load("/Calendar/Data");  //path to the newly created action
}
</script>

Well, you’ve just configured the format of dates (it’s the same as in Data.aspx) and defined the path to action ‘Data’. At this point, the running application will look like this:

Scheduler - Loading the events

Scheduler - Loading the events

We’re halfway there. Just one more step, and we’re almost done.

Step 3 – Saving to the Database

After all the manipulations described above, we’ve built a scheduler which loads the events data from the database, but that’s not enough. Our next goal is to save changes made on the client side to the server. First of all, create one more action – CalendarController.cs:

public ActionResult Save(FormCollection actionValues)
{
String action_type = actionValues["!nativeeditor_status"];
Int64 source_id = Int64.Parse(actionValues["id"]);
Int64 target_id = source_id;

MyEventsDataContext data = new MyEventsDataContext();
Event myevent;
try{
switch (action_type)
{
case "inserted":
myevent = new Event();
myevent.start_date = DateTime.Parse(actionValues["start_date"]);
myevent.end_date = DateTime.Parse(actionValues["end_date"]);
myevent.text = actionValues["text"];
data.Events.InsertOnSubmit(myevent);
break;
case "deleted":
myevent = data.Events.SingleOrDefault(ev => ev.id == source_id);
data.Events.DeleteOnSubmit(myevent);
break;
default: // "updated"
myevent = data.Events.SingleOrDefault(ev => ev.id == source_id);
myevent.start_date = DateTime.Parse(actionValues["start_date"]);
myevent.end_date = DateTime.Parse(actionValues["end_date"]);
myevent.text = actionValues["text"];
break;
}
data.SubmitChanges();
target_id = myevent.id;
}
catch
{
action_type = "error";
}

return View(new CalendarActionResponseModel(action_type, source_id, target_id));
}

It seems that we have a lot of code, but it’s quite simple in its logic. In the first lines, we specify the type of action from the incoming request. Then, depending on the type, we inserted, deleted, or updated the data in the database. And after the DB operation was completed, we rendered a response to the client-side scheduler.

The file Save.aspx will look like this:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<scheduler.ActionResponseModel>" ContentType="text/xml"%>
<data>
<action type="<%= Model.Status %>" sid="<%= Model.Source_id %>" tid="<%= Model.Target_id %>"></action>
</data>

The view shown above uses class ‘CalendarActionResponseModel’ to transfer the necessary information from the action to the view. In CalendarController.cs we add:

public class CalendarActionResponseModel
{
public String Status;
public Int64 Source_id;
public Int64 Target_id;
public CalendarActionResponseModel(String status, Int64 source_id, Int64 target_id)
{
Status = status;
Source_id = source_id;
Target_id = target_id;
}
}

Now update the Index.aspx one more time (add code that will link updates on the client-side scheduler with the action ‘Save’) :

<script type="text/javascript">
function init() {
scheduler.config.xml_date = "%m/%d/%Y %H:%i";
scheduler.init("scheduler_here", new Date(2010, 6, 1), "month");
scheduler.load("/Calendar/Data");

var dp = new dataProcessor("/Calendar/Save");
dp.init(scheduler);
dp.setTransactionMode("POST", false);
}
</script>

If you launch the app now, the screen will look similar to the one from Step 2, but any changes or new events will be saved to the DB. Also, it will correctly restore after page reloading. So now we can proceed to the last step.

Step 4 – Improvements

The code we are using in ‘SaveController’ can be improved by using automatic bindings. In CalendarController.cs:

public ActionResult Save(Event changedEvent, FormCollection actionValues)
{
String action_type = actionValues["!nativeeditor_status"];
Int64 source_id = Int64.Parse(actionValues["id"]);
Int64 target_id = source_id;
MyEventsDataContext data = new MyEventsDataContext();
try{
switch (action_type)
{
case "inserted":
data.Events.InsertOnSubmit(changedEvent);
break;
case "deleted":
changedEvent = data.Events.SingleOrDefault(ev => ev.id == source_id);
data.Events.DeleteOnSubmit(changedEvent);
break;
default: // "updated"
changedEvent = data.Events.SingleOrDefault(ev => ev.id == source_id);
UpdateModel(changedEvent);
break;
}
data.SubmitChanges();
target_id = changedEvent.id;
}
catch
{
action_type = "error";
}
return View(new CalendarActionResponseModel(action_type, source_id, target_id));
}

To give your calendar a slicker and glossier look, or to customize the color scheme, use the online Skin Builder for dhtmlxScheduler. Select one of “Glossy” skins to get a more modern look for the calendar. When you’re done with the customization, download the skin package (.css files and images), and unpack it in the folder ‘‘Scripts’ (it will overwrite some old scheduler files).

The running app after those updates will produce the final look:

Scheduler - Glossy skin

Scheduler - Glossy skin

So let’s see what we’ve got: in just a few steps, we have implemented a web-based calendar that can be used in ASP.NET MVC and provide all the necessary functions: loading, saving, deleting, and updating events.

Of course, perfection knows no bounds. You can define extra fields, add/move calendar views, or redefine the scale and templates configuration (please refer to dhtmlxScheduler documentation). All these changes can be made simply by adding extra JavaScript commands in the “Index” view. There is no need for further updates in the “CalendarController.cs” code. So turn on your imagination and get going!

NOTE: If you’re using VB, please read this comment (many thanks to Brian).

Posted by Ivan Petrenko

Comments

  1. Alexo November 7, 2010 at 12:51 am

    when i update, etc, it show me a alertbox.. i think a have to return someting, in the response, for not show the alertbox and do something to refresh the calendar (ajax etc) because when i insert and then i update it doesnt save the update… i think you do that in “return View(new CalendarActionResponseModel(action_type, source_id, target_id));” but i cant get it =/

  2. Alexo November 7, 2010 at 1:16 am

    Sorry i see it now you do it here ”
    <action type="” sid=”” tid=””>
    ” this xml do the “magic” source = dhtmlxscheduler generated id, target = my db generated id, i just explain if someone have the same rookie trouble..

  3. Craig November 8, 2010 at 4:03 am

    Thanks for doing this blog. It is just what I am looking for.

  4. Joel November 8, 2010 at 7:35 pm

    Umm, for us poor souls stuck using vb .net? any chance of a translation?

    • ivan November 9, 2010 at 12:59 pm

      I’m afraid we do not plan to write a separate tutorial for vb .net.

  5. Artem November 19, 2010 at 9:14 am

    When load this MVC App in browser and when click Save event and when Delete event I’m get alert:
    ——————————————————————————–

    The resource cannot be found.

    body {font-family:”Verdana”;font-weight:normal;font-size: .7em;color:black;}
    p {font-family:”Verdana”;font-weight:normal;color:black;margin-top: -5px}
    b {font-family:”Verdana”;font-weight:bold;color:black;margin-top: -5px}
    H1 { font-family:”Verdana”;font-weight:normal;font-size:18pt;color:red }
    H2 { font-family:”Verdana”;font-weight:normal;font-size:14pt;color:maroon }
    pre {font-family:”Lucida Console”;font-size: .9em}
    .marker {font-weight: bold; color: black;text-decoration: none;}
    .version {color: gray;}
    .error {margin-bottom: 10px;}
    .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }

    <body bgcolor="white"
    Server Error in ‘/’ Application.
    The resource cannot be found.

    Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

    Requested URL: /Shared/Save

    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1

    —————————————————————————–
    What is it?

    • ivan November 19, 2010 at 4:35 pm

      Be sure that path, which is specified at:

      var dp = new dataProcessor(“/Calendar/Save”);

      points to the related Controller (above error looks like mapping is invalid, or incorrect path was specified).

  6. angela November 30, 2010 at 11:53 am

    when do you support multiple users in week view?

  7. Jav January 18, 2011 at 1:07 pm

    Hi, I’m trying to dynamically load events from a controller action depending on what user has selected in the scheduler. I have seen a sample using ASP.NET, I was wondering if you have a sample using ASP MVC? I use custom_data extensively too and so would appreciate if you could explain how to provide this to the page also. I realise you can use connectors to provider data to the scheduler but I’m unsure of the data format to be returned from controller action (JSON?) and also what the signature of the controller action should be. This is a great product by the way (I’ve done a lot of research for scheduler controls and this is tops :-)) Thanks.

    • ivan January 18, 2011 at 2:44 pm

      ” I was wondering if you have a sample using ASP MVC? ”
      This post above explains how to use dhtmlxScheduler with ASP MVC, and it links to the sample:
      http://www.dhtmlx.com/x/download/regular/tutorials/scheduler_aspnet_mvc.zip

      ” but I’m unsure of the data format to be returned from controller action ”
      It can be json or xml:
      http://docs.dhtmlx.com/doku.php?id=dhtmlxscheduler:server_side_integration
      http://docs.dhtmlx.com/doku.php?id=dhtmlxscheduler:loading_from_json

      • Jav January 19, 2011 at 11:49 am

        Hi, thanks for your help, I got this working. This is how I did it:

        // The controller action to receive the data request and respond with valid JSON
        [HttpGet]
        public JsonResult AdminData(string from, string to)
        {

                    var list = new List();

                    list.Add(new DhtmlxEvent()
                                 {
                                     start_date = "2011-01-19 09:15",
                                     end_date = "2011-01-05 09:30",
                                     text = "Test"
               
                                 });
                    list.Add(new DhtmlxEvent() { start_date = "2011-01-19 09:30", end_date = "2011-01-19 09:45", text = "Test 2" });
                    list.Add(new DhtmlxEvent() { start_date = "2011-01-19 11:45", end_date = "2011-01-19 13:00", text = "Test 3" });
                   
                   
                   
                    return Json(list, JsonRequestBehavior.AllowGet);

        }

        // Class structure required by scheduler
        public class DhtmlxEvent
            {
                public DhtmlxEvent()
                {
                    custom_data = new DhtmlxEventCustomData();
                }

                public string start_date { get; set; }
                public string end_date { get; set; }
                public string text { get; set; }
                public DhtmlxEventCustomData custom_data { get; set; }
            }

        // This class can be used to store custom data
            public class DhtmlxEventCustomData
            {
                public int type { get { return 2; }  }
            }

        // Update config of scheduler to call the controller action and set expectation of JSON

        ......
        scheduler.setLoadMode("week");
        scheduler.load('Calendar/AdminData', "json");
  8. Kirk February 10, 2011 at 10:27 am

    Hello receiving error:
    Microsoft JScript runtime error: ‘this.obj.rowsAr’ is null or not an object at line #1581

    if (!this.obj.rowsAr[rowId])

    After a simple of the script, I was unable to locate where rowsAr was initialized.

    Addintional, when starting, a popup opens, which is titled: DataProcessor. There are two sections: Current State and Log, and in the top right corner I have the ability to clear or close. Why has come up.

    I follow the instructions closely.

    Kirk

    • ivan February 10, 2011 at 7:04 pm

      It seems you have included:

      <script src="/Scripts/dhtmlxscheduler_debug.js"

      instead of:

      <script src="/Scripts/dhtmlxscheduler.js"
  9. Kirk February 11, 2011 at 7:47 pm

    Thank you, I changed JS files.

    I’m having an interesting situation. I have two controllers: Home and Calendar. The Calendar controller and Views reflect the tutorial above.

    The Home Controller has only an Index view and comprises of only a single HTML.ActionLink: .

    The interesting part is when I navigate from /Home/Index to /Calendar/Index, I’m able to work with the calendar – adding, removing, updating, etc… However, if I were to navigate back to the the /Home/Index and then navigate back to the calender, all calendar functions don’t work correctly. As, I’m not able to remove, update, or insert events. The Calendar events do display when I navigate back to the calendar.

    If I were to close the browser and reopen it and navigate from Home to Calendar, again I’m able to work with the calendar.

    I seems initially the Data View is return, but when I navigate back from the calendar to home and back to the calendar, the Data View isn’t returned, but the events are displayed on the calendar, yet I’m unable to work with the calendar, which I noticed an exception is throw in the Save Action.

    Kirk

  10. Kirk February 11, 2011 at 9:06 pm

    Working on it a little more, I’ve notice it has something to do with the browser cache.

    Using IE developer tools, after navigating from Home to Calendar and back to Home, I cleared the browser cache, and it seemed to work.

    Kirk

  11. Kirk February 11, 2011 at 9:12 pm

    Since it is an Ajax call, usually every ajax call have a parameter saying not to use cache for jquery

    $.ajaxSetup ({cache: false});

    Kirk

  12. Kirk February 11, 2011 at 9:49 pm

    I was unsuccessful to make it work. I will give it a break, but found an article that might be of interest:
    http://greenash.net.au/thoughts/2006/03/an-ie-ajax-gotcha-page-caching/

  13. Kirk February 12, 2011 at 6:57 pm

    Hello,

    I added this to the header before submitting Ajax request, and it seemed to take of the problem:

    this.xmlDoc.setRequestHeader(“If-Modified-Since”, “Sat, 1 Jan 2005 00:00:00 GMT”);

    Currently have only tested on IE 7, but soon will test on others.

    Below is I inserted the script:
    if (this.async)
    this.xmlDoc.onreadystatechange = new this.waitLoadFunction(this);
    this.xmlDoc.open(postMode ? “POST” : “GET”, filePath, this.async);

    this.xmlDoc.setRequestHeader(“If-Modified-Since”, “Sat, 1 Jan 2005 00:00:00 GMT”);

    if (rpc) {
    this.xmlDoc.setRequestHeader(“User-Agent”, “dhtmlxRPC v0.1 (” + navigator.userAgent + “)”);
    this.xmlDoc.setRequestHeader(“Content-type”, “text/xml”);
    }

    Kirk

  14. nobel codec March 8, 2011 at 6:03 am

    wow! this is also what i’m looking for.

    i am still vs2k8 developer, i will integrate this to my current develop website with asp.net mvc2.

    we will see, how powerful it could be.

    ncodecs

  15. Roger Hampson April 4, 2011 at 5:50 pm

    I am not use Javascript very much at all, so please excuse what may be an obvious question to you.

    If you are trying to setup the calendar on a content page rather than on the master page, what code line do I add the onload=”init()” statement to? I assume it is necessary or the calendar doesn’t get displayed.

    • ivan April 18, 2011 at 8:09 pm

      Instead of onload you can just use:

      <script>
      dhtmlxEvent(window, "load", init);
      </script>

      at the end of the content page (some sizing issues are possible – but the solution must work correctly for most cases).

  16. Celia April 12, 2011 at 11:14 am

    Any sample code is in VB?

  17. Swathi April 26, 2011 at 8:54 am

    Hi,

    I wish to make the size of the application somewhat smaller… May be 1/4th of the whole page as I have to add many other functionalities along with this. Can I change the size of this? Do I need to make changes in the css file??

  18. Prem May 2, 2011 at 1:23 am

    Hi,

    Awesome work and nice calendar.

    But somehow I am getting the error while running it through IIS. It says Scheduler is undefined and due to this my calendar is not working on IIS. I can see scheduler is used in Index.asp, but I couldn’t locate the definition.

    Please help me out with this.

    • ivan May 2, 2011 at 10:02 pm

      Next line at the top of the page:

      <script src="/Scripts/dhtmlxscheduler.js"

      must include the js file, which contains definition of the “scheduler” object.

  19. Roger Hampson June 13, 2011 at 6:29 pm

    I have the scheduler working very nicely with recurring events. I now need to colour code the events into different types of events. I cannot find anything in the documentation where the configuration of the lightbox is explained. How do I alter the lightbox to add another section called “Event Type” showing a pulldown of event types?

    • Paul June 13, 2011 at 8:23 pm

      Please check ‘Details form’ page in our documentation:
      http://docs.dhtmlx.com/doku.php?id=dhtmlxscheduler:custom_details_form

      What you need to change is scheduler.config.lightbox.sections array, e.g.:

      scheduler.config.lightbox.sections=[
      { name:”description”, height:200, map_to:”text”, type:”my_editor”, focus: true },
      { name:”time”, height:72, type:”time”, map_to:”auto” }
      ]

      • Roger Hampson June 14, 2011 at 1:24 pm

        Thanks Paul

        I now have a lightbox with four parts:- Description, Event Type, Repeat Event and Time Period

  20. Roger Hampson June 14, 2011 at 4:56 pm

    I realise that scheduler.config.readonly = true; stops anyone updating the scheduler, but that is not very practical. What I would like is to allow anyone who is in a particular ASP.NET role, say User.IsInRole(“EventEditor”), to be able to update the scheduler, barring all others. I don’t normally use JavaScript so I am having problems putting a test around the scheduler.config.readonly = true; statement so that it is usually true, but false for users within the particualr role. Can you please help?

  21. mush July 15, 2011 at 5:01 pm

    hi
    thnx 4 such a simple but professional example of asp.net mvc with dhtmlxScheduler.
    Im using microsoft visual web developer 2010 express and ms server 2008 R2(express). when i tryied to run this application without any change in code and database then i got this message “Error type:LoadXML Description:Incorrct XML”

    Thanks in advance
    bye

    • Stanislav July 21, 2011 at 12:54 pm

      The error itself just means that server side response is not a valid xml, most probably some error occurs during data generation – you can try to load the data feed in separate window and check the response ( or use dev tools, like firebug, for the same)

  22. will July 16, 2011 at 9:48 am

    hi there, i’m quite new to this, but i follow all step and successfully see the Scheduler..the problem is in step2-Loading Data. when i add the code its show that this line is error :

    MyEventsDataContext data = new MyEventsDataContext();

    its say that the type or namespace ‘MyEventsDataContext’ could not be found (are you missing a using directive or an assembly reference?)

    can anyone help me to fix this? should i declare anything before doing this?
    sorry & thank you for helping me…

  23. will July 16, 2011 at 11:24 am

    ok i fix that problem :)

  24. Brian September 5, 2011 at 11:30 pm

    Just wanted to help out the VB guys. This seems to be working well. DON’T MAKE THE MISTAKE I MADE and run your app and wonder why your dates are not showing up. MAKE SURE THE CALENDAR IS ON THE CORRECT MONTH. It defaults to July 2010. Ugh. How stupid can I be? :D

    Thanks SO MUCH for this component. DHX Rocks!

    Here is Data.aspx:

    <%@ Page Language="VB" Inherits="System.Web.Mvc.ViewPage" ContentType="text/xml" %>
    <data>
    <%  For Each myevent In Model
           Dim currentEvent = myevent%>
    <event id="<%=currentEvent.id%>">
    <start_date><![CDATA[<%= String.Format("{0:MM/dd/yyyy HH:mm}",currentEvent.start_date) %>]]></start_date>
    <end_date><![CDATA[<%= String.Format("{0:MM/dd/yyyy HH:mm}",currentEvent.end_date) %>]]></end_date>
    <text><![CDATA[<%= currentEvent.text%>]]></text>
    </event>
    <%  Next%>
    </data>

    Here’s Save.aspx:

    <%@ Page Language="VB" Inherits="System.Web.Mvc.ViewPage" ContentType="text/xml"%>
    <data>
    <action type="<%= Model.Status %>" sid="<%= Model.Source_id %>" tid="<%= Model.Target_id %>"></action>
    </data>

    Here’s Index.aspx:

    <%@ Page Language="VB" Inherits="System.Web.Mvc.ViewPage" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head id="Head1" runat="server">
    <title>Index</title>
    <script src="/Scripts/dhtmlxscheduler.js" type="text/javascript"></script>
    <script type="text/javascript" src="../../Scripts/dhtmlxscheduler_recurring.js"></script>
    <link href="/Scripts/dhtmlxscheduler.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
    html, body
    {
    height:100%;
    padding:0px;
    margin:0px;
    }
    </style>
    <script type="text/javascript">
        function init() {
            scheduler.config.xml_date = "%m/%d/%Y %H:%i";
            scheduler.init("scheduler_here", new Date(2010, 6, 1), "month");
            scheduler.load("/Calendar/Data");

            var dp = new dataProcessor("/Calendar/Save");
            dp.init(scheduler);
            dp.setTransactionMode("POST", false);
        }
    </script>
    </head>
    <body onload="init()">
    <div id="scheduler_here" class="dhx_cal_container" style='width:100%; height:100%;'>
    <div class="dhx_cal_navline">
    <div class="dhx_cal_prev_button">&nbsp;</div>
    <div class="dhx_cal_next_button">&nbsp;</div>
    <div class="dhx_cal_today_button"></div>
    <div class="dhx_cal_date"></div>
    <!-- div class="dhx_cal_tab" name="day_tab" style="right:204px;"></div>
    <div class="dhx_cal_tab" name="week_tab" style="right:140px;"></div -->
    <div class="dhx_cal_tab" name="month_tab" style="right:76px;"></div>
    </div>
    <div class="dhx_cal_header">
    </div>
    <div class="dhx_cal_data">
    </div>
    </div>
    </body>
    </html>

    Here’s CalendarController.vb:

    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Web
    Imports System.Web.Mvc
    'Imports MyCalendar.Models

    Namespace MyCalendar.Controllers
        Public Class CalendarActionResponseModel
            Public Status As [String]
            Public Source_id As Int64
            Public Target_id As Int64

            Public Sub New(ByVal status__1 As [String], ByVal source_id__2 As Int64, ByVal target_id__3 As Int64)
                Status = status__1
                Source_id = source_id__2
                Target_id = target_id__3
            End Sub
        End Class

        Public Class CalendarController
            Inherits Controller
            '
           ' GET: /Calendar/

            Public Function Index() As ActionResult
                Return View()
            End Function

            Public Function Data() As ActionResult
                Dim data__1 As New MyEventsDataContext()
                Return View(data__1.Events)
            End Function

            Public Function Save(ByVal changedEvent As [Event], ByVal actionValues As FormCollection) As ActionResult
                Dim action_type As [String] = actionValues("!nativeeditor_status")
                Dim source_id As Int64 = Int64.Parse(actionValues("id"))
                Dim target_id As Int64 = source_id


                Dim data As New MyEventsDataContext()
                Try
                    Select Case action_type
                        Case "inserted"
                            data.Events.InsertOnSubmit(changedEvent)
                            Exit Select
                        Case "deleted"
                            changedEvent = data.Events.SingleOrDefault(Function(ev) ev.id = source_id)
                            data.Events.DeleteOnSubmit(changedEvent)
                            Exit Select
                        Case Else
                            ' "updated"
                           changedEvent = data.Events.SingleOrDefault(Function(ev) ev.id = source_id)
                            UpdateModel(changedEvent)
                            Exit Select
                    End Select
                    data.SubmitChanges()
                    target_id = changedEvent.id
                Catch
                    action_type = "error"
                End Try

                Return View(New CalendarActionResponseModel(action_type, source_id, target_id))
            End Function
        End Class
    End Namespace

    Here is Global.asax.vb:

    ' Note: For instructions on enabling IIS6 or IIS7 classic mode,
    ' visit http://go.microsoft.com/?LinkId=9394802

    Public Class MvcApplication
        Inherits System.Web.HttpApplication

        Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

            ' MapRoute takes the following parameters, in order:
           ' (1) Route name
           ' (2) URL with parameters
           ' (3) Parameter defaults
           routes.MapRoute( _
                "Default", _
                "{controller}/{action}/{id}", _
                New With {.controller = "Calendar", .action = "Index", .id = UrlParameter.Optional} _
            )

        End Sub

        Sub Application_Start()
            AreaRegistration.RegisterAllAreas()

            RegisterRoutes(RouteTable.Routes)
        End Sub
    End Class

    Zip file with all above code can be downloaded from:
    http://support.dhtmlx.com/x-files/scheduler_3_0/DHTMLXSchedulerMVC-VB.zip

    • Dave Miller December 8, 2011 at 10:26 pm

      Tried the vb version.
      I got an error: “MyEventsDataContext” is not defined?
      Can you tell what I’ve done wrong?

      • Aliaksandr December 9, 2011 at 1:01 pm

        Hi,
        try to uncomment line
        ‘Imports MyCalendar.Models
        in CalendarController.vb

  25. GIANG September 13, 2011 at 7:16 am

    How ? ! Add mini calendar to Event calendar

  26. Bao form VietNam October 21, 2011 at 11:14 am

    hi all! I’m very thank for all
    Now I need project framwork v3.5 or slower for Event Calendar

    I’m doing a module on the management of work schedules for DotNetNuke
    So who are or have suggestions about how to share that module for me?
    I am very thankful
    And can send email for me
    ( p.s: Tôi mới học viết tiếng anh )

  27. Om Thoke October 21, 2011 at 9:58 pm

    Wow this looks like a cool blog for coders!

  28. Bao form VietNam October 23, 2011 at 12:44 pm

    I can project use version .Net framework 3.5 or slow
    who have project can send for me! email : chibao2704@gmail.com
    Best Regards!

    thank alllll

  29. Frank October 31, 2011 at 3:10 pm

    Any chance for an example using MVC 3 and Razor?

  30. Yash November 16, 2011 at 4:01 am

    +1 for MVC 3.0 and Razor.

    • Ivan November 16, 2011 at 3:33 pm

      Please see the link above.

    • Frank November 18, 2011 at 5:58 pm

      Is there a way to set the calendar so that no changes can be made to it, i.e. so users can basically view the events, navigate, and do nothing else? I want to have one version that staff here can edit and another version that just displays events. Is that possible?

      • fodendo November 19, 2011 at 5:16 pm

        sure,
        scheduler.config.readonly = true; – it will block any changes in calendar
        also take a look at the next post,
        http://www.dhtmlx.com/blog/?p=1291

  31. Tom December 29, 2011 at 8:25 pm

    I am getting the following script error on loading. I believe that I have it set up correctly. Do you have any idea what I am missing? Thanks!

    ‘getElementsByTagName’: object is null or undefined

    • Aliaksandr December 30, 2011 at 1:19 pm

      Looks like data response has contained incorrect xml, maybe app has failed to connect to your database,
      see response from data request(/Calendar/Data) it should have the error description

  32. Jeremy January 31, 2012 at 11:54 am

    Hello,
    Can you send me video of this event calendar. Because i want to see how to creat this event calender.

  33. Honey February 6, 2012 at 12:36 pm

    Is it ok if I’m follow this tutorial without using MVC? Is it also working for normal website application rather than MVC application?

    • Ivan February 6, 2012 at 4:01 pm

      Yes, it will also work for normal website application.There is nothing that can’t be done without MVC.

  34. vijay February 6, 2012 at 1:22 pm

    how to make time slot in 15mnts,?

    now it is 30 mints i want to do it 15mints how can i do……….?

    thank you.

  35. Honey February 7, 2012 at 4:49 pm

    Hello, how can i do this step? I’m not really understand about this step. I’m new to this. Please help me…
    – the updating of a default route. Switch the default route of the app to the newly-created controller in Global.asax.cs:

    public static void RegisterRoutes(RouteCollection routes)
    {
    routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);

    routes.MapRoute(
    “Default”, // Route name
    “{controller}/{action}/{id}”, // URL with parameters
    new { controller = “Calendar”, action = “Index”, id = UrlParameter.Optional } // Parameter defaults
    );
    }

    • Aliaksandr February 7, 2012 at 5:49 pm

      Since you are not using mvc.net, you may just skip this part. Routing are essential for mvc applications, in web forms apps you can do without it.
      This article has more info about routing in asp.net
      http://msdn.microsoft.com/en-us/library/cc668201.aspx

      • Honey February 7, 2012 at 7:51 pm

        oo i see..thank you.
        I’m sorry for asking. How about Step 2 – Loading Data? How the process actually? If possible, can u teach me in more specific about it because seriously i need to understand that. I’m in the learning process to complete my project for my department.

  36. Honey February 8, 2012 at 1:54 am

    how the step to loading data actually? I get an error…because I did not use mvc.net… Maybe it could be a different step that I need to follow from the step above?

  37. Honey February 8, 2012 at 9:02 am

    How can i add a controller because i’m not using mvc? Please help me.

    • Aliaksandr February 8, 2012 at 12:36 pm

      you can’t use controllers in not-mvc project,
      you may use webform+codebehind(e.g. data.aspx + data.aspx.cs), or generic handlers( .ashx) to implement the same logic as in views+actions from the tutorial, the code will be almost the same, except that you’ll be passing model to .aspx page as property of the class from codebehind.
      please, submit further technical questions to our forum:)
      http://forum.dhtmlx.com/viewforum.php?f=6

  38. Honey February 8, 2012 at 2:11 pm

    I have the generic handlers but my event did not save in the database. what should i do?

  39. Ignacio February 24, 2012 at 8:39 pm

    Hi!
    I am trying to render the calendar inside a View that it is inside the Layout(as if it were a partialView) with MVC3 Razor.
    If I remove the @Layout=null the calendar disappears and if I set again it doesn’t consider the layout.
    Could you give me any advise on how to do it?

    Thanks in advance!

    • Ivan February 28, 2012 at 4:37 pm

      Ignacio, please create a topic on the forum and attach a demo (or code snippet) where the scheduler does not work with the layout. It’s hard to say something specific about this issue. It looks like there is a conflict between styles of the Scheduler (or container in which it is drawn) and layout.
      You can access the forum here (registration is free):
      http://forum.dhtmlx.com/

  40. Ivaylo March 7, 2012 at 8:32 pm

    Hi,
    I am using mvc 4 and in my controller I can’t call the InsertOnSubmit method. Instead I use the AddObject().
    But it seems that it doesn’t work it doesn’t save my events in the db. Where could the problem be? Thanks in advance.

  41. My real name April 11, 2012 at 12:13 am

    I am using example for MVC3 above (MVC3, VS10, .NET 4).
    No matter what I do (login, logout with “test” user, hardcode scheduler.config.readonly to “false” etc etc, I cannot insert, update and delete events, only see and navigate.
    I can see however, that when event is supposed to be editable the mouse changes its form from arrow to hand with index finger, but clicking and double clicking doesn’t do anything. Also clicking and double clicking
    on the background (not on event) does nothing either.
    What can be a problem, please?!

  42. Surya April 22, 2012 at 2:32 pm

    I am trying to use example given below
    link:http://dhtmlx.com//x/download/regular/tutorials/scheduler_booking.zip
    But this is always returing changedEvent.start_date and changedEvent.end_date is null, so data could not be able to saved in DB. Do you have any workaround of this?

    • Ivan May 2, 2012 at 3:38 pm

      Try to change date format in scheduler.config.xml_date and Data.aspx to your local datetime format. The issue happens because model binder expects dates to be sent in local CultureInfo date format.

  43. raghav April 23, 2012 at 1:15 pm

    Hi!
    I am trying to render the calendar inside a View that it is inside the Layout(as if it were a partialView) with MVC3 Razor.
    If I remove the @Layout=null the calendar disappears and if I set again it doesn’t consider the layout.
    Could you give me any advise on how to do it?

    Thanks in advance!

    • Aliaksandr April 27, 2012 at 8:49 pm

      Hi,
      check styles of the scheduler container. It must have a valid size in pixels of percents. If size defined in percents – be sure that parent container has some height settings as well.

  44. raghav April 24, 2012 at 2:37 pm

    i want to add more fields in dialogue box which comes with start date ,end date ,description

    same i want add one label with text area called event name
    then what should i do

  45. anees April 28, 2012 at 3:47 pm

    how can i load calender inside div not on body?

    • Ivan May 2, 2012 at 2:37 pm

      You just need to put the markup of the Scheduler inside the div. The only requirement – the div should have some non-zero height, otherwise the calendar won’t be rendered.

  46. Bill May 8, 2012 at 2:32 am

    Hi. This seems to work great in my the root of my html, but if it is within s or , the calendar disappears. Is it possible to not run this full screen? I would like a smaller calendar within my page.

    Thank you.

    • Bill May 8, 2012 at 2:42 am

      Incidentally, I have been able to get this to work using an iFrame. Is there a cleaner way?

      • Aliaksandr May 8, 2012 at 4:04 pm

        Hi,
        scheduler can be placed anywhere on the page, but its container must have initial sizes set. Otherwise calendar will be displayed incorrectly. e.g. you should have smth like follows

        <div id="scheduler_here" …

        • Aliaksandr May 8, 2012 at 4:09 pm

          sorry, once again, html could look like:
          <div style=”height:500px;width:700px” >
          <div id=”scheduler_here” …

          </div>
          </div>

  47. Grab July 13, 2012 at 3:06 pm

    Hello,
    I am trying to test DHTMLXSchedular MVC Application with MySQL Database.

    Please let me know steps for the same.

    Thanks in Advance.

    Regards,
    Grab.

  48. Lyle July 18, 2012 at 8:24 pm

    Here is how to initialize the scheduler to the current date as well as working with Master Pages.

    There is no “body” tag but the solution is fairly simple… in the view:

    <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
        <style>
            html, body
            {
                height: 100%;
                padding: 0px;
                margin: 0px;
            }
        </style>    
        <script src="" type="text/javascript">
        
            function body_onload() {
                scheduler.config.xml_date = "%m/%d/%Y %H:%i";

                var today = new Date();
                scheduler.init("scheduler_here", new Date(today.getFullYear(), today.getMonth(), today.getDate()), "month");
                scheduler.load("");

                var dp = new dataProcessor("");
                dp.init(scheduler);
                dp.setTransactionMode("POST", false);
            }
        </script>
    </asp:Content>

    As you can see, “scheduler.init” now has the current date set in the function “body_onload()”.

    To invoke the “body_onload()” function add this to the Site.Master page:

            function mp_onload() {
                if (window.body_onload != null)
                    window.body_onload();
            }
       


    ...

    This allows the execution of the “body onload=” function in any of your pages in your site.

    Happy Coding!

  49. Lyle July 18, 2012 at 8:43 pm

    Ivan,

    My apologies, I did not realize that the text for content place holders would not be displayed until after I posted so the following needs to be added to the above post.

    I placed the code for both the “view” and the Site.Master page in the ContentPlaceHolder “HeadContent”.

    Just for clarity, in the view page the div id=”scheduler_here” and all of the underlying divs are placed in the ContentPlaceHolder “MainContent”. I also changed the style on this div to “position:absolute; width: 95%; height: 500px;” which you will need to play with to figure out how it looks best on your site.

    Now if anyone knows how I can get IE8 to display the time correctly from the CDATA contents I would love to hear from them!

    • Ivan July 19, 2012 at 5:16 pm

      I’ve edited your comment so it should now display the code correctly (I hope). Thank you for your contribution.

  50. Forestier August 15, 2012 at 8:42 pm

    Hello,

    I use the following routemap in my routeconfig.cs :

    routes.MapRoute(
    “App”,
    “{org}/{controller}/{action}/{id}”,
    new { controller = “Home”, action = “Index”, id = UrlParameter.Optional });

    In this case, your control doesn’t work. I got this error :

    The controller for path “/BasicScheduler/Data” was not found or does not implement IController.

    If I come back to your maproute sample it works but in my case, I really need the “{org}” part.

    Do you have any advise ?

    Thanks,

    • Ivan August 17, 2012 at 3:04 pm

      You can specify paths to the controllers and actions. For that, you need:

      1) create a scheduler object by default constructor (i.e. without parameters). In this case standard paths (like “/BasicScheduler/Data”) won’t be generated.

      var scheduler = new DHXScheduler();

      2) if the scheduler is initialized this way, you can specify the full URLs to save and load handlers:

      scheduler.DataAction = “org/controller/action”;
      scheduler.SaveAction = “org/controller/save”;

      All above is said for DHTMLX Scheduler .NET. If you use the standard JavaScript scheduler (dhtmlxScheduler), you can see where the path is specified.

  51. Deepa March 13, 2013 at 5:32 am

    Not compatible with IE9

    • Ivan March 16, 2013 at 8:25 pm

      Please provide more details on what is not working in IE9.

  52. hieudt May 28, 2013 at 7:32 am

    Using VS2k8 and MVC2, I got problem at scheduler.load(“/Calendar/Data”), it seems this path is not correct, I changed it to scheduler.load(“/vn/Calendar/Data”) but still not working, data not load to scheduler
    I use the following routemap in my Global.asax.cs :
    routes.MapRoute(
    “Default”, // Route name
    “{language}/{controller}/{action}/{id}”, // URL with parameters
    new { language = “vn”, controller = “Calendar”, action = “Index”, id = UrlParameter.Optional }
    );
    Any suggestion ?

  53. hieudt May 29, 2013 at 1:03 pm

    I solved it, change “/Calendar/Data” to full URL and done.
    Another question : how can I change the text “New event” when inserting new record, I want the text change to “Type your Name”, “Thing you want to do”, etc…

  54. paul July 31, 2013 at 2:11 am

    Hi

    Have you any advice on .cshtml/razor engine rendering? I can follow aspx steps but cshtml does not display scheduled control?

    Cheers

  55. Eric Bauwens August 23, 2013 at 10:58 am

    Do you have a version that works on .NET 3.5 framework? – Thanks much.

    • Ivan August 23, 2013 at 8:39 pm

      Eric, you can use DHTMLX Scheduler .NET, the ASP.NET version of the scheduler, that works in ASP.NET framework 3.5.

  56. Pallav Joshi August 2, 2014 at 1:18 pm

    Hey,
    Thanks for the great article.It works like a charm.

    • Ivan (DHTMLX team) August 4, 2014 at 1:04 pm

      Thank you for your kind words.:) We appreciate it.

  57. Pallav Joshi August 4, 2014 at 10:44 am

    Hi,It is working fine without the layout page but when i put this in a view having some layout it does not dispaly anything.plz help.its urgent

  58. archie December 11, 2014 at 12:57 pm

    hi,
    how can i delete na event to the calendar?

    • Ivan (DHTMLX team) December 12, 2014 at 1:44 pm

      Hi, please elaborate your question.
      There is a UI control for deleting event on the page, client side method and server side method.
      What exactly do you need?

  59. Dibesh Kumart October 26, 2015 at 10:45 am

    Hi,I am using oracle 10g database.how to insert,update,delete through asp.net mvc 4 razor engine.

  60. Rajesh2K15 November 20, 2015 at 11:24 am

    Hi…First of all thanks for the great post and it’s really a life saver. My request is can you please convert Data.aspx and Save.aspx view into equivalent Razor view as i’m finding difficulty in implementing them in my MVC5 application.

  61. Rajesh2K15 November 20, 2015 at 2:30 pm

    Can you please tell me the need of using Data.aspx i.e., what actually we are doing there and can you convert Data.aspx into Data.cshtml view since all my views are in .cshtml form.

Leave a Reply