Skip to main content
Home  › ... Razor

WebApi Tutorials

Tutorial HomeWebApi

App Query WebApi Examples

In this example, we'll get app-data from the WebApi which runs a query with a parameter.

Click to see the result of a WebApi call with the shared code:

Output

@{
  var authorId = AsDynamic(App.Data["Persons"].First()).EntityId;
}
<button type="button" class="btn btn-primary" onclick="getAuthor(this, @authorId)">
  Get Author #@authorId
</button> 
  @* 2sxclint:disable:no-inline-script *@
<script>
  function getAuthor(moduleContext, authorId) {
    $2sxc(moduleContext).webApi.fetchJson('authorsquery/get?authorId=' + authorId)
      .then(function (author) {
        alert('Found author: '
          + author.FirstName + ' ' + author.LastName 
          + ' (with ' + author.Books.length + ' books) \n\n'
          + 'The raw JSON: \n' + JSON.stringify(author)
          );
      });    
    }
</script>

Source Code of ../api/AuthorsQueryController.cs

// Add namespaces for security check in Oqtane & DNN despite differences in .net core/.net Framework
// If you only target one platform, you can remove the parts you don't need
#if NETCOREAPP
using Microsoft.AspNetCore.Authorization; // .net core [AllowAnonymous] & [Authorize]
using Microsoft.AspNetCore.Mvc;           // .net core [HttpGet] / [HttpPost] etc.
#else
using System.Web.Http;                    // .net 4.5 [AllowAnonymous] / [HttpGet]
using DotNetNuke.Web.Api;                 // [DnnModuleAuthorize] & [ValidateAntiForgeryToken]
#endif
using System.Linq;                        // this enables .First() or .Select(x => ...)

// Tutorial note: This is used in the WebApi demos for Querying App Data

[AllowAnonymous]                          // all commands can be accessed without a login
[ValidateAntiForgeryToken]                // protects API from users not on your site (CSRF protection)
public class AuthorsQueryController : Custom.Hybrid.Api14 // see https://r.2sxc.org/CustomWebApi
{
  [HttpGet]                               // [HttpGet] says we're listening to GET requests
  public dynamic Get(int authorId)
  {
    var query = Kit.Data.GetQuery("AuthorsWithBooks", parameters: new {
      AuthorId = authorId
    });
    
    var a = AsDynamic(query["Current"].First());

    return new {
        Id = a.EntityId,
        a.FirstName,
        a.LastName,
        Picture = a.Mugshot,
        Books = AsList(query["CurrentBooks"])
          .Select(b => new {
            Id = b.EntityId,
            b.Title
          })
      };
  }

}

// The next line is for 2sxc-internal quality checks, you can ignore this
// 2sxclint:disable:no-dnn-namespaces - 2sxclint:disable:no-web-namespace

Source Code of this file

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

@inherits Custom.Hybrid.Razor14
<!-- unimportant stuff, hidden -->


<div @Sys.PageParts.InfoWrapper()>
  @Html.Partial("../shared/DefaultInfoSection.cshtml")
  <div @Sys.PageParts.InfoIntro()>
      <h2>App Query WebApi Examples</h2>
      <p>
        In this example, we'll get app-data from the WebApi which runs a query with a parameter. 
      </p>

      <p>
        Click to see the result of a WebApi call with the shared code:  
      </p>
    </div>
  </div>

  @{
    var authorId = AsDynamic(App.Data["Persons"].First()).EntityId;
  }
  <button type="button" class="btn btn-primary" onclick="getAuthor(this, @authorId)">
    Get Author #@authorId
  </button> 
    @* 2sxclint:disable:no-inline-script *@
  <script>
    function getAuthor(moduleContext, authorId) {
      $2sxc(moduleContext).webApi.fetchJson('authorsquery/get?authorId=' + authorId)
        .then(function (author) {
          alert('Found author: '
            + author.FirstName + ' ' + author.LastName 
            + ' (with ' + author.Books.length + ' books) \n\n'
            + 'The raw JSON: \n' + JSON.stringify(author)
            );
        });    
      }
  </script>



@* Footer *@
@Html.Partial("../Shared/Layout/FooterWithSource.cshtml", new { Sys = Sys })