1

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;
}

2 Answers 2

0

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.

0

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%>")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.