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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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