Copied to clipboard

Flag this post as spam?

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


  • Adam Wróbel 1 post 71 karma points
    May 17, 2022 @ 15:55
    Adam Wróbel
    0

    Get value definied in Umbraco CMS on C# method level

    Hello everyone 👋

    A few hours ago I started my adventure with Umbraco (and so far everything has been great) and I have come to the point where I need to use the declared value with Umbraco CMS on c# method level:

    public class WeatherViewComponent : ViewComponent
    {
        public IViewComponentResult Invoke()
        {
            //get city name definied in Umbraco CMS
            var city = ???;
    
            var weather = getWeather(city);
            return View("Default",weather);
        }
    }
    

    enter image description here

    In documentation, I read about IPublisdehContent and I try do something like this :

    public class WeatherViewComponent : ViewComponent
    {
        private readonly IPublishedContent _publishedContent;
    
        public TwitterViewComponent(IPublishedContent publishedContent)
        {
            _publishedContent = publishedContent;
        }
    
        public IViewComponentResult Invoke()
        {
            var city = _publishedContent.Value("city");
    
            var weather = getWeather(city);
            return View("Default",weather);
        }
    }
    

    But in this case i got error Unable to resolve service for type 'Umbraco.Cms.Core.Models.PublishedContent.IPublishedContent'

  • Paul Seal 510 posts 2791 karma points MVP 5x c-trib
    May 17, 2022 @ 22:03
    Paul Seal
    0

    Hi

    I think you might have over complicated it slightly. Try doing this:

    public class WeatherViewComponent : ViewComponent
    {
        [ViewComponent(Name = "Weather")]
        public IViewComponentResult Invoke(IPublishedContent content)
        {
            var city = content.Value<string>("city");
    
            var weather = getWeather(city);
            return View("Default",weather);
        }
    }
    

    Kind regards

    Paul

Please Sign in or register to post replies

Write your reply to:

Draft