Skip to main content

knockoutjs with Umbraco and Umbraco base call

I was thinking how we could use knockoutjs with Umbraco, so just thought blog it.

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.
  • Features
  • Elegant dependency tracking
  • Declarative bindings
  • Flexible and sophisticated templating
  • Trivially extensible

More information reference: http://knockoutjs.com.

Well, we start with Umbraco, To know more on umbraco, Please refer below links
http://our.umbraco.org/wiki/how-tos/a-complete-newbie's-guide-to-umbraco
http://umbraco.com/help-and-support/video-tutorials/getting-started?freeVideos=1
http://our.umbraco.org/wiki/how-tos/getting-started-with-umbraco-what-is-next-after-you-install
http://our.umbraco.org/wiki/install-and-setup

I have created a document with document type "Announcement" with below two properties
  • announcementTitle 
  • description
My Html block is as shown below
<p>
        <h1 data-bind="text: Title">
        </h1>
    </p>
    <p>
        <span data-bind="html: Description"></span>
    </p>
    <form id="frmAnnoumcent">
    <p>
        Title:
        <input data-bind="value: Title" name="Title" style="width: 400px" /></p>
    <p>
        Annoucement:
        <textarea data-bind="value: Description" name="Description" rows="5" cols="60"> </textarea></p>
    <button data-bind="click: save">
        Save Listings</button>
    </form>

Script Block

    <script type="text/javascript">

    var announcement = {
        "Title": ko.observable("") ,
        "Description": ko.observable(""),
    };
  
   var viewModel=ko.mapping.fromJS(announcement);
     $.ajax({
        url: '/base/baseCall/GetAnnouncement.aspx',
        type: "POST",
        data: $('#frmTest').serialize(),
        dataType: 'JSON',
        success: function(result)
        {
            ko.mapping.fromJS(result,{},viewModel);
          
        },
        error:
        function(result)
        {
        alert(result.message);
        }
       
    });
  
    viewModel.save = function() {
    $.ajax({
        url: '/base/baseCall/SaveAnnouncement.aspx',
        type: "POST",
        data: $('#frmTest').serialize(),
        dataType: 'JSON',
        success: function(result)
        {

            ko.mapping.fromJS(result,{},viewModel);
             ko.applyBindings(viewModel);
          
        },
        error:
        function(result)
        {
        alert(result.message);
        }
       
    });
},
$(function() {
    ko.applyBindings(viewModel);
});
     </script>

Base Service Call

       [RestExtension("baseCall")]
    public class TestService
    {
        [RestExtensionMethod(returnXml = false)]
        public static string SaveAnnouncement()
        {
            DocumentType dt = DocumentType.GetByAlias("Announcement");
            User author = User.GetUser(0);

            string title = HttpContext.Current.Request["Title"];
            string Description = HttpContext.Current.Request["Description"];

            Document doc = Document.MakeNew(title, dt, author, 1048);
            doc.getProperty("announcementTitle").Value = title;
            doc.getProperty("description").Value = Description;
            //after creating the document, prepare it for publishing

            doc.Publish(author);

            //Tell umbraco to publish the document
            umbraco.library.UpdateDocumentCache(doc.Id);

            return GetAnnouncement();
        }
        [RestExtensionMethod(returnXml=false)]
        public static string GetAnnouncement()
        {

            List<Announcement> announcement = new List<Announcement>();
            Document root = new Document(1048);
            string sJSON="";
            if (root.HasChildren)
            {
                foreach (Document tempDocument in root.Children.OrderByDescending(res => res.CreateDateTime))
                {
                    Announcement a = new Announcement();
                    Property prop1 = tempDocument.getProperty("announcementTitle");

                    a.Title = (string)prop1.Value;
                    prop1 = tempDocument.getProperty("description");
                    a.Description = (string)prop1.Value;
                    announcement.Add(a);
                    System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
        new System.Web.Script.Serialization.JavaScriptSerializer();
                    sJSON = oSerializer.Serialize(a);

                    sJSON=sJSON.Insert(sJSON.Length - 2, ",");
                    break;
                }
            }
          
            return sJSON;
        }



    }
    public class Announcement
    {
        public string Title { get; set; }
        public string Description { get; set; }
    }

Of-course the knockoutjs can be used well, and it gives an live UI. We could create an amazing user experience with it.

Comments

Popular posts from this blog

Why not to have a static const in c#

This is just a thought, that I was thinking why can't we have a constant with static in C#, and the answer is 'NO'; That we cannot have a static constant; e.g: I created a class as below: public class Constants1 { public const string Const1 = "Hello"; public const string Const2 = "World"; public static string Static1 = "Hello Static"; } When we compile the program into IL, the C# compiler does a magic in IL, that the constants converts into static literals, of course it has to, that's why we are able to access the constants as Constants1.Const1

Beyond Solo Assistants: Google's Vision for AI Teamwork (Agent-to-Agent Collaboration)

We talk a lot about AI assistants like Google Assistant or chatbots answering our questions. They're pretty smart on their own, right? But imagine if they could team up, combine their unique skills, and tackle really complex problems together, just like a human team does. That's the core idea behind a super exciting area Google and others in the AI world are exploring: Agent-to-Agent (A2A) communication and collaboration. Think of it less as a single product called "Agent2Agent" and more as the science and engineering of building AI teams. Ready to explore why this is such a big deal? Let's break it down! First Off: What Even is an AI Agent? Think of an AI agent as a specialized digital helper. It's a piece of software designed to: Perceive: Understand its environment (text, images, data, user requests). Reason: Figure out the best course of action based on its goals and knowledge. Act: Perform tasks (answer questions, writ...

Create Document Dynamically (Umbraco)

You can create document and publish the content during run time, Below code snippets helps you to do it. public class UmbracoUtils { /// <summary> /// Create and publish the document programatically /// </summary> /// <param name="nodeName"></param> /// <param name="properties"></param> /// <param name="documentType"></param> /// <param name="parentId"></param> /// <returns>node id</returns> public static int CreateDocument(string nodeName, Dictionary<string, string> properties, int documentType, int parentId, List<string> roles = null) { DocumentType dt = new DocumentType(documentType); umbraco.BusinessLogic.User u = new umbraco.BusinessLogic.User(0); // Create the document Document d = Document.MakeNew(nodeName, dt, u, parentId); // Add values...