Skip to main content Skip to footer

Working with ASP.NET Core Razor Pages

GrapeCity has released ASP.NET Core 2.0-compatible bits through the GrapeCity NuGet. As of today, you can use ASP.NET MVC Edition Core controls in your ASP.NET Core 2.0 applications. ASP.NET Core 2.0 added an excellent feature called Razor Pages that enables easy page-focused application development. You can use advanced UI controls with Razor Pages; the HtmlHelpers and TagHelpers just work. In this blog, we'll walk through using FlexGrid to display sales information on a page.

Project

  • Create a new web application using the ASP.NET Core Web Application template.
  • Select “Web Application” in the next screen.
  • The application should show the following files in solution explorer:

Razor Pages Web Application

Data:

Add a model folder to the project. We'll add a simple Sales class to it.

public class Sales
    {        
        public int ID { get; set; }
        public DateTime Start { get; set; }
        public DateTime End { get; set; }
        public string Country { get; set; }
        public string Product { get; set; }
        public string Color { get; set; }
        public double Amount { get; set; }
        public double Amount2 { get; set; }
        public double Discount { get; set; }
        public bool Active { get; set; }

        public MonthData[] Trends { get; set; }
        public int Rank { get; set; }

        /// <summary>
        /// Get the data.
        /// </summary>
        /// <param name="total"></param>
        /// <returns></returns>

        public static IEnumerable<Sale> GetData(int total)
        {
            var countries = new[] { "US", "UK", "Canada", "Japan", "China", "France", "German", "Italy", "Korea", "Australia" };
            var products = new[] { "Widget", "Gadget", "Doohickey" };
            var colors = new[] { "Black", "White", "Red", "Green", "Blue" };
            var rand = new Random(0);
            var dt = DateTime.Now;
            var list = Enumerable.Range(0, total).Select(i =>
            {
                var country = countries[rand.Next(0, countries.Length - 1)];
                var product = products[rand.Next(0, products.Length - 1)];
                var color = colors[rand.Next(0, colors.Length - 1)];
                var date = new DateTime(dt.Year, i % 12 + 1, 25, i % 24, i % 60, i % 60);

                return new Sale
                {
                    ID = i + 1,
                    Start = date,
                    End = date,
                    Country = country,
                    Product = product,
                    Color = color,
                    Amount = rand.NextDouble() * 10000 - 5000,
                    Amount2 = rand.NextDouble() * 10000 - 5000,
                    Discount = rand.NextDouble() / 4,
                    Active = (i % 4 == 0),
                    Trends = Enumerable.Range(0, 12).Select(x => new MonthData { Month = x + 1, Data = rand.Next(0, 100) }).ToArray(),
                    Rank = rand.Next(1, 6)
                };
            });
            return list;
        }
    }
    public class MonthData
    {
        public int Month { get; set; }
        public double Data { get; set; }
    }
}

Razor Page

Now that we have the model available, let’s see how to display the model data using a FlexGrid on Razor Page:

  • Add C1.AspNetCore.MVC package from GrapeCity NuGet, build 1.0.20172.131 and later support ASP.NET Core 2.0. Refer to the documentation for NuGet details.
  • Add the following style and scripting resources to Layout.cshtml page in the header:
<c1-styles></c1-styles>
<c1-scripts>
    <c1-basic-scripts></c1-basic-scripts>
</c1-scripts>

Now that we have the package, resources and license in place, we can start using the controls on the Razor Pages.

  • Open the Index.cshtml.cs file and import the Models namespace.
  • In the IndexModel class, add a public variable “salesList” of type List.
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SalesReport.Models;

namespace SalesReport.Pages
{
    public class IndexModel : PageModel
    {
       public List<Sales> salesList = Sales.GetData(25).ToList();
       public void OnGet()
        {

        }
    }
}
  • Open the Index.cshtml page and clear the content the except the following:
@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}
  • Declare FlexGrid as follows:
<c1-flex-grid  id="fg" auto-generate-columns="true">
      <c1-items-source  source-collection="Model.salesList"  page-size="10"></c1-items-source>
</c1-flex-grid>
<c1-pager  owner="fg"></c1-pager>

Note that the public property “salesList” is available to us using the Model. We assign it to the source-collection of FlexGrid and set paging related properties.

That's all we need to get the FlexGrid up and running. Run the application to view sales data.

Binding to JSON Data from ActionResults

Like MVC, it's possible to bind the grid with data returned by a remote action. Using the same example, we add the “onPostDataBind” ActionResult to return data in JSON format to the IndexModel class:

public class IndexModel : PageModel
    {
    public void OnGet()
        {

        }

        public ActionResult OnPostDataBind([C1JsonRequest]CollectionViewRequest<Sales> requestData)
        {
            return JsonConvertHelper.C1Json(CollectionViewHelper.Read(requestData, Sales.GetData(25)));
        }
    }

Note that the function is prefixed with “OnPost.” it is convention for Razor Pages. A post handler (the method is called a handler in Razor Pages) should have prefix like OnPostXXX/OnGetXXX or OnPostXXXAsync/OnGetXXXAsync for asynchronous calling.

Now update the FlexGrid declaration on Index.cshtml Razor Page, to use remote binding:

@Html.AntiForgeryToken()
  <c1-flex-grid  id="fg" auto-generate-columns="true">
    <c1-items-source read-action-url="@Url.Page("Index",  "DataBind")" page-size="10"></c1-items-source>
  </c1-flex-grid>
  <c1-pager  owner="fg"></c1-pager>

Here, we set the read-action-url FlexGrid’s item-source to the action we defined in the IndexModel class. The @UrlPage takes two parameters. First is the name of the Razor Page, and the second is name of the action.

Note that we added the AntiForgeryToken. This token is for preventing cross-site request forgery attack; anti-forgery token generation and validation are automatically included in Razor Pages. Here, Remote binding calls a handler to get data so we needed to add it. In the case of model binding, it does not need to call a handler, so model binding doesn't require an explicitly-added token.

Now we've seen how easy it is to develop web pages using Razor Pages! Together with TagHelpers, this becomes a great rapid application development tool.

Try ComponentOne Studio Enterprise

Prabhakar Mishra

Prabhakar Mishra

Product Manager
comments powered by Disqus