Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Tim Bennett 23 posts 155 karma points
    Apr 21, 2021 @ 07:58
    Tim Bennett
    0

    Passing data to JavaScript

    Hiya,

    I've been building with Umbraco for a while now, but admittedly at a pretty novice level, so please forgive me if this ends up being a really obvious answer!

    Currently if I want to pass data over to my JS I use either data attributes or hidden divs. That's fine for a variable here and there, but I find myself having to put complex objects in there too and end up with rendered HTML that's very dense, exposes all data, and I guess is potentially slower?

    There's got to be better way! A custom API? Am I finally going to have to learn how to MVC?

    I'm got no problem going off and teaching myself whatever I need to learn, I'm just struggling to work out what it is I need to study!

  • Matthew Wise 271 posts 1373 karma points MVP 4x c-trib
    Apr 21, 2021 @ 08:47
    Matthew Wise
    0

    Hi Tim,

    Sounds like you want a Web API, so you can call it from your JS and return a JSON object (or whatever you want/ need).

    Umbraco does have some documentation on them here - https://our.umbraco.com/documentation/Reference/Routing/WebApi/

    Hopefully this is enough to get you started :)

    Good luck and keep learning

    Matt

  • Tim Bennett 23 posts 155 karma points
    Apr 21, 2021 @ 09:06
    Tim Bennett
    0

    Yes! This is exactly what I need, I'm surprised I hadn't found that page in the documentation, I really should stop researching things half awake in the middle of the night! Thanks Matt

  • Lee Kelleher 4020 posts 15802 karma points MVP 13x admin c-trib
    Apr 21, 2021 @ 09:17
    Lee Kelleher
    1

    Following on from using data- attributes, often to create less friction between frontend and backend devs, we'll use a Global object for page-level data.

    Apologies if I'm teaching anyone to suck eggs.

    e.g. at the bottom of the page, we'd have.

    <script>var PAGE = { "key": "value", "alias": "foo" };</script>
    

    The Razor would be something like this...

    <script>var PAGE = @Html.Raw(JsonConvert.SerializeObject(pageData));</script>
    

    Where the pageData would be some sort of key/value pairs, e.g. a Dictionary<string, object> or JObject. Sometimes it'd be stored a Request.Item to collect data between partial-views, etc. Like most things in Umbraco, there's a gazillion ways to do it.

    Note, I generally put the Html.Raw/JsonConvert bits in an extension method, only to hide the ugliness away.

    All that said, there's nothing wrong with the WebApi approach, just mentioning how I'd been tackling it when working with frontend devs. e.g. they put everything they need in the Global object, and I swap it out later.

    Cheers,
    - Lee

Please Sign in or register to post replies

Write your reply to:

Draft