Sitecore API and JavaScript

Forms now a days are rather interactive.  Ajax calls to update some aspect of a form are common.  In this post I will show you how to take a child list of items, send it through a Sitecore API call, and populate a drop down with JavaScript.  Our example will be populating a drop down from a list of states using MVC.  We will assume that you know how to create that child list of items in Sitecore.  We will also assume that you know how to populate that list to a model.

First step is to create your drop down in a view rendering.

@Html.DropDownListFor(x => x.FormModel.States, Model.States, new {id = "state-select" })

Default values could be used to pre-populate before JavaScript load gets a hold of it.  In our instance, the value is blank as all is populated client side.

The next step would be to look at the JSON we would want to create.  In this case its pretty simple:

{"states":[{"id":"stateguid","displayName":"state"},{"id":"stateguid","displayName":"state"}]}

In order to get to this state we need to create a model, populate our model with data from Sitecore, and then using Newtonsoft to serialize the object.  I use http://json2csharp.com/  to make the model building process super simple.  The above JSON produces the following model class:

public class State
{
     public string id { get; set; }
     public string displayName { get; set; }
}

public class RootObject
{
    public List states { get; set; }
}

Next you need a controller.  I have created a StateController with the ActionResult of GetAllStates.  This will open up the default api call of /api/Sitecore/State/GetAllStates .  Our StateItemModel populates our list of Sitecore child items (not shown).   Here is the core of the code:

public ActionResult GetAllStates()
{

     StateItemModel stateModel = new StateItemModel();

     RootObject stateJson = (new RootObject { states= GetStateList(stateModel .States) });

     return Content(JsonConvert.SerializeObject(stateJson), "application/json");
}

private List<State> GetStateList(List<StateItemModel> stateItems)
{
     List<State> stateList = new List<StateArea>();
     foreach (var stateItem in stateItems)
     {
          stateList.Add(new Area { id = stateItem.Id, displayName = stateItem.Title });
     }
     stateList = stateList .OrderBy(v => v.displayName).ToList();
     return stateList ;
}

Finally to pull it all together you need some javascript to read your JSON:

$(document).ready(function () {

        $.getJSON("/api/Sitecore/State/GetAllStates", function (data) {
            appendInputs(data, $('#state-select'));
        });
}

function appendInputs(data, location) {
    $.each(_.sortBy(data.states), function (i, state) {
        if (!state.id || !state.displayName) return;
        location.append('<option value="' + state.id + '">' + state.displayName + '</option>');
    });
}

Overall this is a really simple example and could be handled server side. But it has some practical use. If anything it will get you started on building more complex calls in your forms.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s