Try our conversational search powered by Generative AI!

Loading...
Area: Optimizely CMS

Recommended reading 

Gadget development, step 1: Showing information

Models

Add a Message class to the Models directory of the QuickChat project.

XML
using System;
                namespace QuickChat.Models
                {
                   public class Message
                     {
                       public string Text { get; set; }
                       public string From { get; set; }
                       public DateTime Sent { get; set; }
                    }
                }
The model describes the data you interact with using the controller and show in your views.

Controller

Going back to the QuickChatController and use EPiServer.Data to retrieve messages from the database (take a look at the Dynamic Data Store section):

C#
[Gadget]
          public class QuickChatController : Controller
          {
               // since the controller is created for each request
               // we can assign a store as a variable
               static QuickChatController()
               {
                    DynamicDataStoreFactory.Instance.CreateStore(typeof(Message));
                         }
                    DynamicDataStore store = 
            DynamicDataStoreFactory.Instance.GetStore(typeof(Message));
                public ActionResult Index()
                {
                 // select all messages for the last 5 minutes
                    var fiveMinutesAgo = DateTime.Now.AddMinutes(-5);
                    var messages = from m in store.Items<Message>()
                        where m.Sent > fiveMinutesAgo
                        select m;
                 // pass the messages to the view
                  return View(messages.ToList());
            }}

The code selects recent messages and passes them to the Index view for display.

Views

Create an MVC partial view in the QuickChat project.

 

To activate the wizard, right-click in the controller action and select Add view (requires ASP.NET MVC to be installed).

When you locate the view in Views/QuickChat/Index.ascx in the QuickChat project, it is selected automatically to show the messages.

<%@ Control Language="C#" 
       Inherits="System.Web.Mvc.ViewUserControl<IList<QuickChat.Models.Message>>" %>
          <%@ Import Namespace="QuickChat.Models" %>
             <div class="epi-defaultPadding">
                <ul>
                   <% foreach (Message m in Model) { %>
                     <li><%= m.From %>: <%= m.Text %></li>
                         <% } %>
                </ul>
                Number of messages: <%= Model.Count %>
           </div>

The view shows messages passed to it by the controller.

Next steps

Do you find this information helpful? Please log in to provide feedback.

Last updated: Nov 25, 2015

Recommended reading