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

    Umbraco 8 Partial View macro accessing database


    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

    Hi Gevorg

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

    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()
                        var countries = scope.Database.Query<MyCountryTable>(sql);
     var vm = new CountriesListViewModel();
    vm.Countries = countries;
                    return View("CountriesListPartial", vm);

    or similar...



Please Sign in or register to post replies

Write your reply to: