Copied to clipboard

Flag this post as spam?

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


  • dan 54 posts 133 karma points
    Aug 09, 2015 @ 17:44
    dan
    0

    MediaPicker Object to JSON using WebAPI

    Is it possible to serialize a mediapickers contents to json? So it could be something like this....

    Example:

    { ['name':'muffin', 'file':'muffin.jpg', 'text':'some text'], ['name':'gargamel', 'file':'smurf.jpg', 'text':'some more text'] }
    

    I can see around there are ways to convert C# variables to javascript, but I'm a bit unsure where to put the code for it or whats the best way to do it?

    I found this link to serialize using a helper function but I don't know how/where to add this as an extension.

    https://iterativo.wordpress.com/2013/04/04/converting-c-razor-models-into-javascript-objects/

    Thanks!

  • Carl Jackson 139 posts 478 karma points
    Aug 10, 2015 @ 15:37
    Carl Jackson
    0

    You can use the newtonsoft json library to serialise / deserialize just about any c# poco object to/from json

    http://www.newtonsoft.com/json/help/html/SerializingJSON.htm

    Are you wanting to do this fromnt end or backend?

    Do you have any code currently?

    Thanks

  • dan 54 posts 133 karma points
    Aug 10, 2015 @ 16:35
    dan
    0

    I don't have anything mocked up. Only figured out recently that after trying few things that Razor doesn't support passing to js with @HTML and

    My ideal setup is if its on the front end, I could code with it on the fly converting umbraco objects for use in js in my templates. I'm not clear how it would work as a back end item.

  • Carl Jackson 139 posts 478 karma points
    Aug 11, 2015 @ 16:35
    Carl Jackson
    0

    If you need the data in JS you can use an API controller to return the media object as JSON (look at umbraco web api)

    You would use an ajax request to get this with the media id passed to the API controller.

    Any use?

  • dan 54 posts 133 karma points
    Aug 11, 2015 @ 19:23
    dan
    0

    Thanks Carl,

    I did find the https://our.umbraco.org/documentation/Reference/WebApi/ link.

    I don't have any problems with making ajax calls but the learning curve with where to start writing the C# for this, I'm lost.

    Writing the C# I can understand the syntax but where to put it, how to reference it in Umbraco, or how to reference it in the editor are the questions I'm trying to grasp.

  • Carl Jackson 139 posts 478 karma points
    Aug 12, 2015 @ 08:15
    Carl Jackson
    0

    Hi Dan

    The web API is pretty simple hopefully.

    You would need a model to return (the media info)

    eg

    public class MediaApiModel
    {
        public int MediaId { get; set; }
    
        public string MediaUrl { get; set; }
    
        // etc for all required properties
    }
    

    A controller with one action eg

    public class MediaApiController : UmbracoApiController
    {
    
        public MediaApiModel GetMediaById(int id)
        {
            var media = Umbraco.TypedMedia(id);
    
            return new MediaApiModel
            {
                MediaId = media.Id,
                MediaUrl = media.Url
                // etc until all properties are set
            };
    
        } 
    }
    

    and then from ajax you would call the URL "/Umbraco/Api/MediaApi/GetMediaById" and pass the required id as post data. That will return you the MediaApiModel formated as Json data.

    Thanks

    Carl

  • dan 54 posts 133 karma points
    Aug 14, 2015 @ 17:02
    dan
    0

    Hey Carl,

    So I found a similar example which is namespaced and has some hard coded data into an object to reference but I'm not able to get this service to work. The service comes up 404 error.

    The model script, is living in the Models folder and the controller is in the Controllers folder.

    //Model

    namespace ProductsApp.Models
    {
        public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Category { get; set; }
            public decimal Price { get; set; }
        }
    }
    

    //Controller

    using ProductsApp.Models
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Web.Http;
    
    namespace ProductsApp.Controllers
    {
    
        public class ProductsController : UmbracoApiController
        {
            Product[] products = new Product[] 
            { 
                new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
                new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
                new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
            };
    
            public IEnumerable<Product> GetAllProducts()
            {
                return products;
            }
    
            public IHttpActionResult GetProduct(int id)
            {
                var product = products.FirstOrDefault((p) => p.Id == id);
                if (product == null)
                {
                    return NotFound();
                }
                return Ok(product);
            }
        }
    }
    

    ///JavaScript

     var uri = 'Umbraco/Api/Products/';
    
        $(document).ready(function () {
          // Send an AJAX request
          $.getJSON(uri)
              .done(function (data) {
                // On success, 'data' contains a list of products.
                $.each(data, function (key, item) {
                  // Add a list item for the product.
                  $('<li>', { text: formatItem(item) }).appendTo($('#products'));
                });
              });
        });
    
        function formatItem(item) {
          return item.Name + ': $' + item.Price;
        }
    
        function find() {
          var id = $('#prodId').val();
          $.getJSON(uri + '/' + id)
              .done(function (data) {
                $('#product').text(formatItem(data));
              })
              .fail(function (jqXHR, textStatus, err) {
                $('#product').text('Error: ' + err);
              });
        }
    
  • Carl Jackson 139 posts 478 karma points
    Aug 17, 2015 @ 08:04
    Carl Jackson
    1

    Hi Dan, Are you running this on a local machine?

    The file locations shouldn't be an issue, Have done a build of the code in visual studio?

    Also just noticed - the namespace "ProductsApp" needs to be your root namespace of your project if it isn't already

    This is why we don't put namespaces into code snippets as everyone's will be different :)

    Thanks

  • dan 54 posts 133 karma points
    Aug 21, 2015 @ 15:31
    dan
    0

    I converted my project to be a web app instead of web site in visual studio. Its nearly there; the simpler webAPI methods are finally working properly.

    Now, the only problem I have is converting a mediapicker to a json object.

Please Sign in or register to post replies

Write your reply to:

Draft