Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I am developing a web part currently which has custom attributes which are defined through C#, but most of the logic has been completed using javascript. I am having trouble getting the attributes passed in to the javascript functions, as they're in a separate module.

How can I access web Part Custom attributes through javascript if that is even possible? Below is essentially my main() function which needs to have access to the web part's attributes.

$.ready(webPartLoaded);

function webPartLoaded() {
    getPic();
    var myImg = document.getElementById("myImgId");
    //myImg.onmousedown = GetCoordinates;
}
share|improve this question

2 Answers 2

I'm not sure if this is the best approach, but at least it should work (theory):

protected override void CreateChildControls() {
    var script = new HtmlGenericControl 
    {
        TagName = "script",
        InnerHtml = JsonConvert.SerializeObject(webPartAttributes)
    };
    script.Attributes.Add("type", "application/json");
    script.Attributes.Add("id", "data");
    Controls.Add(script);
}

Then in your JavaScript you can do:

var config = JSON.parse($('#data').text());

Note that I use JSON.NET, which you must add to Packages. You can alternatively use JavaScriptSerializer.

share|improve this answer
up vote 0 down vote accepted

I ended up figuring out how to reference a c# object property from within an associated javascript file.

Within my webPart class I included

    [WebBrowsable(true),
     WebDisplayName("PicName"),
     WebDescription("Title of Picture"),
     Personalizable(PersonalizationScope.Shared),
     Category("Custom Category")]
    public string TextProperty { get; set; }

Within the javascript I included this to reference TextProperty:

    console.log("object prop: <%=TextProperty%>")
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.