Search This Blog

Saturday, September 12, 2015

Populate Drop Down Lists in Client Object Model

SharePoint 2010 provided two major custom web part enhancements: Visual Web Parts and Client Side

 Object Model (COM) using JavaScript. We can populate a dropdown items from a sharepoint list.

First populate a list for example : InterviewerList

In visual webpart add following tag in .ascx file inside a DIV tag :

<select id="ddlInterviewerName">

</select>

Then jump to your .js file and write following code :



jQuery(document).ready(function () {

    ExecuteOrDelayUntilScriptLoaded(function () {
        obj = new ScheduleInterviewClass();
        obj.LoadObjects();
    }, "sp.js");
});


function ScheduleInterviewClass() {

    this.LoadObjects = LoadObjects;

    var siteObjects = {
        ctx: null,
        web: null,
        url: null,
        InterviewerList: null,
        InterviewerListItems: null
    };

    
    function LoadObjects() {
        siteObjects.ctx = SP.ClientContext.get_current();
        siteObjects.web = siteObjects.ctx.get_web();
        siteObjects.ctx.load(siteObjects.web);
        siteObjects.ctx.executeQueryAsync(Function.createDelegate(this, LoadObjectsOnSuccess), Function.createDelegate
       (this, LoadObjectsOnFailure));
    }

    function LoadObjectsOnSuccess() {

        siteObjects.InterviewerList = siteObjects.web.get_lists().getByTitle("InterviewerList");      
        var query = new SP.CamlQuery();
        query.set_viewXml();

        siteObjects.InterviewerListItems = siteObjects.InterviewerList.getItems(query);

        siteObjects.ctx.load(siteObjects.InterviewerListItems);
        siteObjects.ctx.executeQueryAsync(Function.createDelegate(null, RenderHtmlOnSuccess), Function.createDelegate(null, RenderHtmlOnFailure));
    }

    function LoadObjectsOnFailure() {
        alert("Objects Not Loaded Properly. Try again");
    }

    function RenderHtmlOnSuccess() {
        var ddlInterviewer = this.document.getElementById("ddlInterviewerName");
        ddlInterviewer.options.length = 0;
        var enumerator = siteObjects.InterviewerListItems.getEnumerator();

        while (enumerator.moveNext()) {
            var currentItem = enumerator.get_current();
            ddlInterviewer.options[ddlInterviewer.options.length] = new Option(currentItem.get_item
("InterviewerName").get_lookupValue(), currentItem.get_item("ID"));                    
        }
    }


    function RenderHtmlOnFailure(sender, args) {
        alert(args.get_message());
        alert("Not able to render HTML");
    }



}

No comments:

Post a Comment