Search results

Calculated Field in ASP.NET MVC Pivot Table control

Allows end user to create a new calculated field in the pivot table, based on available fields from the bound data source or using simple formula with basic arithmetic operators. It can be added at runtime through the built-in dialog, invoked from Field List UI. To do so, set the AllowCalculatedField property in PivotView class to true in the pivot table. End user can now see a “CALCULATED FIELD” button enabled in Field List UI automatically, which on clicking will invoke the calculated field dialog and perform necessary operation.

Calculated field can also be included in the pivot table through code behind using the PivotViewCalculatedFieldsSettings class. The required properties to create a new calculate field are:

  • Name: It allows to indicate the calculated field with a unique name.
  • Formula: It allows to set the formula.
  • Format: It helps to set the number format for the resultant value.

The calculated field is applicable only for value fields. Also, calculated field created through code behind will be automatically listed in the UI dialog as well.

razor
calculatedfield.cs
@{var amount = "\"" + "Sum(Amount)" + "\"";}
@{var sold = "\"" + "Sum(Sold)" + "\"";}
@{ var totalPrice = amount + "+" + sold;}

@Html.EJS().PivotView("PivotView").Height(300).DataSourceSettings(dataSource => dataSource.DataSource((IEnumerable<object>)ViewBag.DataSource).ExpandAll(false).EnableSorting(true)
 .FormatSettings(formatsettings =>
 {
     formatsettings.Name("Amount").Format("C0").MaximumSignificantDigits(10).MinimumSignificantDigits(1).UseGrouping(true).Add();
     formatsettings.Name("Total").Format("C0").Add();
 }).Rows(rows =>
 {
     rows.Name("Country").Add(); rows.Name("Products").Add();
 }).Columns(columns =>
 {
     columns.Name("Year").Caption("Year").Add(); columns.Name("Quarter").Add();
 }).Values(values =>
 {
     values.Name("Sold").Caption("Units Sold").Add(); values.Name("Amount").Caption("Sold Amount").Add();
     values.Name("Total").Type(Syncfusion.EJ2.PivotView.SummaryTypes.CalculatedField).Add();
 }).CalculatedFieldSettings(calculatedfieldsettings =>
 {
     calculatedfieldsettings.Name("Total").Formula(totalPrice).Add();
 })).AllowCalculatedField(true).ShowFieldList(true).Render()
public ActionResult Index()
{
    var data = GetPivotData();
    ViewBag.DataSource = data;
    return View();
}

output

Meanwhile, user can also view calculated field dialog in UI by invoking CreateCalculatedFieldDialog method on an external button click which is shown in the below code sample.

razor
calculatedfield.cs
@{var amount = "\"" + "Sum(Amount)" + "\"";}
@{var sold = "\"" + "Sum(Sold)" + "\"";}
@{ var totalPrice = amount + "+" + sold;}

@Html.EJS().Button("calculated-field-btn").Content("Calculated Field").IsPrimary(true).Render()
@Html.EJS().PivotView("PivotView").Height("300").DataSourceSettings(dataSource => dataSource.DataSource((IEnumerable<object>)ViewBag.DataSource).ExpandAll(false).EnableSorting(true)
 .FormatSettings(formatsettings =>
 {
     formatsettings.Name("Amount").Format("C0").MaximumSignificantDigits(10).MinimumSignificantDigits(1).UseGrouping(true).Add();
     formatsettings.Name("Total").Format("C0").Add();
 }).Rows(rows =>
 {
     rows.Name("Country").Add(); rows.Name("Products").Add();
 }).Columns(columns =>
 {
     columns.Name("Year").Caption("Year").Add(); columns.Name("Quarter").Add();
 }).Values(values =>
 {
     values.Name("Sold").Caption("Units Sold").Add(); values.Name("Amount").Caption("Sold Amount").Add();
     values.Name("Total").Type(Syncfusion.EJ2.PivotView.SummaryTypes.CalculatedField).Add();
 }).CalculatedFieldSettings(calculatedfieldsettings =>
 {
     calculatedfieldsettings.Name("Total").Formula(totalPrice).Add();
 })).AllowCalculatedField(true).ShowFieldList(true).Render()

<script>
        document.getElementById("calculated-field-btn").addEventListener('click', function () {
            var pivotObj = document.getElementById("PivotView").ej2_instances[0];
            pivotObj.createCalculatedFieldDialog();
        });
</script>
public IActionResult Index()
{
    var data = GetPivotData();
    ViewBag.DataSource = data;
    return View();
}

output

output

Editing through the field list and the grouping bar

User can also modify the existing calculated field using the built-in edit option available directly in the field list (or) grouping bar. To do so, click the “Edit” icon available in the calculated field button. Now the calculated field dialog is opened and the current calculated field name, formula and format can be changed at runtime.

output

output

Renaming the existing calculated field

Existing calculated field can be renamed only through the UI at runtime. To do so, open the calculated field dialog, select the target field and click “Edit” icon. User can now see the existing name getting displayed in the text box at the top of the dialog. Now, change the name based on user requirement and click “OK”.

output

output

Editing the existing calculated field formula

Existing calculated field formula can be edited only through the UI at runtime. To do so, open the calculated field dialog, select the target field and click “Edit” icon. User can now see the existing formula getting displayed in a multiline text box at the bottom of the dialog. Now, change the formula based on user requirement and click “OK”.

output

output

Reusing the existing formula in a new calculate field

While creating a new calculated field, if user wants to the add the formula of an existing calculated field, it can be done easily. To do so, simply drag-and-drop the existing calculated field to the “Formula” section.

output

output

output

Apply the format to the calculated field values

The values in the new or existing calculated field can be formatted through its UI and also through code behind. To format the calculated field values at runtime, the built-in textbox is available under the “Format” label where the user can set the desired format. Likewise, in code-behind, you can set the desired format using the FormatSettings property as illustrated in the introduction section. For more information about the supported formats refer here.

output

Supported operators and functions for the calculated field formula

Below is a list of operators and functions that can be used in the formula to create the calculated fields.

  • + – addition operator.
 Syntax: X + Y
  • - – subtraction operator.
Syntax: X - Y
  • * – multiplication operator.
Syntax: X * Y
  • / – division operator.
Syntax: X / Y
  • ^ – power operator.
Syntax: X^2
  • < - less than operator.
Syntax: X < Y
  • <= – less than or equal operator.
Syntax: X <= Y
  • > – greater than operator.
Syntax: X > Y
  • >= – greater than or equal operator.
Syntax: X >= Y
  • == – equal operator.
Syntax: X == Y
  • != – not equal operator.
Syntax: X != Y
  • | – OR operator.
Syntax: X | Y
  • & – AND operator.
Syntax: X & Y
  • ? – conditional operator.
Syntax: condition ? then : else
  • isNaN – function that checks if the value is not a number.
Syntax: isNaN(value)
  • !isNaN – function that checks if the value is a number.
Syntax: isNaN(value)
  • abs – function that returns the absolute value of a number.
Syntax: abs(number)
  • min – function that returns the minimum value.
Syntax: min(number1, number2)
  • max – function that returns the maximum value.
Syntax: max(number1, number2)

Also, you can use JavaScript Math object properties and methods directly to the formula.

razor
calculatedfield.cs
@{ var totalPrice = "\"" + "Math.round(" + "\"" + "Sum(Amount)" + "\"" + ") > abs(" + "\"" + "Sum(Sold)" + "\"" + ") ? min(" + "\"" + "Sum(Amount)" + "\"" + "," + "\"" + "Sum(Sold)" + "\"" + ") : Math.sqrt(" + "\"" + "Sum(Sold)" + "\"" + ")";}

@Html.EJS().PivotView("PivotView").Height(300).DataSourceSettings(dataSource => dataSource.DataSource((IEnumerable<object>)ViewBag.DataSource).ExpandAll(false).EnableSorting(true)
 .FormatSettings(formatsettings =>
 {
     formatsettings.Name("Amount").Format("C0").MaximumSignificantDigits(10).MinimumSignificantDigits(1).UseGrouping(true).Add();
 }).Rows(rows =>
 {
     rows.Name("Country").Add(); rows.Name("Products").Add();
 }).Columns(columns =>
 {
     columns.Name("Year").Caption("Year").Add(); columns.Name("Quarter").Add();
 }).Values(values =>
 {
     values.Name("Sold").Caption("Units Sold").Add(); values.Name("Amount").Caption("Sold Amount").Add();
     values.Name("Total").Type(Syncfusion.EJ2.PivotView.SummaryTypes.CalculatedField).Add();
 }).CalculatedFieldSettings(calculatedfieldsettings =>
 {
     calculatedfieldsettings.Name("Total").Formula(totalPrice).Add();
 })).AllowCalculatedField(true).ShowFieldList(true).Render()
public ActionResult Index()
{
    var data = GetPivotData();
    ViewBag.DataSource = data;
    return View();
}

output

Event

CalculatedFieldCreate

The event CalculatedFieldCreate fires while closing the dialog on “OK” button click. It allows to customize the new or existing calculated field information obtained from the dialog. It has the following parameters

  • calculatedField: It holds the new or existing calculated field information obtained from dialog.
  • calculatedFieldSettings: It holds the calculatedFieldSettings property of the pivot report.
  • cancel: It is a boolean property and by setting this to true , the customization done in calculated field dialog won’t be applied to calculated field.

In the below sample, creating a calculated field without setting the format is restricted.

razor
calculatedfieldCreate.cs
@{var amount = "\"" + "Sum(Amount)" + "\"";}
@{var sold = "\"" + "Sum(Sold)" + "\"";}
@{ var totalPrice = amount + "+" + sold;}

@Html.EJS().PivotView("PivotView").Height(300).DataSourceSettings(dataSource => dataSource.DataSource((IEnumerable<object>)ViewBag.DataSource).ExpandAll(false).EnableSorting(true)
 .FormatSettings(formatsettings =>
 {
     formatsettings.Name("Amount").Format("C0").MaximumSignificantDigits(10).MinimumSignificantDigits(1).UseGrouping(true).Add();
 }).Rows(rows =>
 {
     rows.Name("Country").Add(); rows.Name("Products").Add();
 }).Columns(columns =>
 {
     columns.Name("Year").Caption("Year").Add(); columns.Name("Quarter").Add();
 }).Values(values =>
 {
     values.Name("Sold").Caption("Units Sold").Add(); values.Name("Amount").Caption("Sold Amount").Add();
     values.Name("Total").Type(Syncfusion.EJ2.PivotView.SummaryTypes.CalculatedField).Add();
 }).CalculatedFieldSettings(calculatedfieldsettings =>
 {
     calculatedfieldsettings.Name("Total").Formula(totalPrice).Add();
 })).AllowCalculatedField(true).ShowFieldList(true).CalculatedFieldCreate("calculatedFieldCreate").Render()
 <script>
    function calculatedFieldCreate(args) {
       if(args.calculatedField.formatString === '') {
            args.cancel = true;
        }      
    }
</script>
public ActionResult Index()
{
    var data = GetPivotData();
    ViewBag.DataSource = data;
    return View();
}