Copied to clipboard

Flag this post as spam?

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


  • Gevorg 13 posts 124 karma points
    Sep 23, 2019 @ 07:37
    Gevorg
    0

    Umbraco 8 Partial View macro accessing database

    Hello,

    I had a macro working for Umbraco V7 which read a list of countries from custom table and displayed as HTML select on website. Can you please give an example how it can be achieved in Umbraco V8? I cannot access the db context on custom controller and call the controller from partial view macro in V8 anymore.

  • Marc Goodson 1678 posts 11074 karma points MVP 6x c-trib
    Sep 23, 2019 @ 21:06
    Marc Goodson
    100

    Hi Gevorg

    I think in V8 you can access the database to run custom queries against a custom table via using a Scope...

    github.com/umbraco/Umbraco-CMS/blob/853087a75044b814df458457dc9a1f778cc89749/src/Umbraco.Core/Scoping/IScope.cs

    There is a ScopeProvider that has the job of creating a 'scope' object from which you can access the IUmbracoDatabase or run your SQL...

    You can 'inject' the ScopeProvider into your custom controller...

    So something like this:

        using System.Linq;
        using System.Web.Mvc;
        using Umbraco.Core.Persistence;
        using Umbraco.Core.Scoping;
        using Umbraco.Web.Mvc;
    
        namespace YourSiteNamespace.Controllers
        {
            public class CountriesController : SurfaceController
            {
                private readonly IScopeProvider scopeProvider;
    
                public CountriesController(IScopeProvider scopeProvider)
                {
                    this.scopeProvider = scopeProvider;
                }
                // GET: Countries
                public ActionResult GetCountries()
                {
                    using (var scope = scopeProvider.CreateScope(autoComplete: true))
                    {
                        var sql = scope.SqlContext.Sql()
                            .Select("*")
                            .Where<MyCountryTable>(f=>f.IsCountry).OrderBy<MyCountryTable>(f=>f.CountryName);
    
                        var countries = scope.Database.Query<MyCountryTable>(sql);
                    }
     var vm = new CountriesListViewModel();
    vm.Countries = countries;
                    return View("CountriesListPartial", vm);
                }
            }
    }
    

    or similar...

    regards

    Marc

Please Sign in or register to post replies

Write your reply to:

Draft