Still using Radzen Studio?
Achieve more with Radzen Blazor Studio

Radzen Blazor Studio is our new flagship product and vision of how rapid Blazor application development should be done.

Go to Radzen Blazor Studio

Invoke method (Blazor)

Custom business logic is key to most applications - call a third party API, execute complex database query or perform some calculation and return its result.

In Blazor applications Radzen supports this scenario out of the box via the Invoke method action type.

Introduction

Radzen generates a <page-name>.razor.cs file for every page. You can add methods to that file which you can then execute.

Let’s create a method which returns the sum of its arguments.

  1. Add a new page to your Radzen application called Sum.
  2. Open the server\Pages\Sum.razor.cs file in your your code editor of choice.
  3. Add the following method to the empty SumComponent partial class.
    public int Sum(int x, int y)
    {
        return x + y;
    }
    
  4. Drag and drop a Button component in a Radzen page.
  5. Handle the Click event of the Button.
    • Set the Type of the action to Invoke method.
    • Select the Sum method from the dropdown. Radzen will load all methods of the page that you can invoke. If you don’t see your method yet - click the reload button next to the dropdown.
    • Specify the arguments for the x and y parameters of the Sum method.
  6. This will invoke the custom method. But we also need its result. Handle the Then event of the invoke.
    • Set the Type of the action to Show notification.
    • Set Severity to info.
    • Set Summary to ${result}. But what does ${result} mean? The result keyword is a placeholder which means “the result of the current custom method”. Then sum is the property which our custom method happens to use to return its result.

Now run the application to test the Sum method.

Here is what happened:

  1. When you click the button the event handler executes the custom Sum method with parameters x=1 and y=2.
  2. Radzen allows you to use the result of a custom methodsfor various purposes - for example to display it as a notification.

Get user input

Now let’s pass the user input to the custom method. If you need a refreshment on getting user input in Radzen check the Properties help article.

  1. Create two page properties - x and y. They will store the user input and be the arguments of the Sum method.
  2. Drag and drop two Numeric components. Data-bind the first component to x and the second to y.
  3. Edit the Click event handler of the button from the previous section. Set the x parameter to ${x} and the y parameter to ${y}. This will use the values of the x and y properties as method arguments.

Run the application to see it in action.

Perform custom database query

The previous examples used the sample custom method which doesn’t do anything particularly useful. Let’s do something real-life instead such as making a database query and returning its result. As usual we will use the Northwind database.

Create the custom method that executes the DB query

Let’s make the method return the number of orders that ship to a user specified country.

  1. Add a new MSSQL data source for the Northwind database. You can check the MSSQL help topic for additional instructions.
  2. Add a new empty page Orders to your application.
  3. Open the server\Pages\Orders.razor.cs file with your code editor.
  4. Inject the Entity Framework context created for the Northwind database as a property decorated with the Inject attribute.
    [Inject]
    NorthwindContext NorthwindContext { get; set; }
    
  5. Add a new method to the OrdersComponent class. It will return the number of orders that ship to the specified country.
    public int OrdersByCountry(string country)
    {
        var orders = NorthwindContext.Orders.Where(o => o.ShipCountry == country);
    
        return orders.Count();
    }
    

Create the UI

The UI will be simple:

  • a textbox to capture the user input (the country)
  • a button which will invoke the custom method and display the result

Follow these steps:

  1. Create a new page in your application.
  2. Drag and drop a TextBox and a Button.
  3. Create a page property called country and data-bind the TextBox to that property.
  4. Handle the Click event of the Button.
    • Set the action Type to Invoke method
    • Pick the OrdersByCountry method from the dropdown.
    • Set the country parameter to ${country}.
  5. Handle the Then event of the Invoke method to display the result.
    • Set the action Type to Show notification.
    • Set Severity to info.
    • Set Summary to Orders: ${result}

Run the application to try it:

Display DB query in a DataGrid

Another common task is to display the result of a custom DB query in a DataGrid. We will use again the Northwind database and will display the number of orders per ShipCity in a DataGrid component.

  1. Make sure you have a MSSQL data source for the Northwind database.
  2. Add a new class in the Orders.razor.cs file.
    public class OrderByCity
    {
       public string ShipCity { get; set; }
       public int Count { get; set; }
    }
    
  3. Add a new method to the OrdersComponent partial class
    public IEnumerable<OrderByCity> OrdersByCity()
    {
        var orders = NorthwindContext.Orders.GroupBy(o => o.ShipCity)
                     .Select(group => new OrderByCity() {
                        ShipCity = group.Key,
                        Count = group.Count()
                     });
    
    
        return orders;
    }
    
  4. Drag and drop a DataGrid component.
  5. Add a new event handler for the Page Load event.
    • Set Type to Invoke method
    • Pick the OrdersByCity method.
  6. Handle the Then event of the Invoke method created in the previous step.
    • Set Type to Set property. We want to store the result of the OrdersByCity method so we can use it with the DataGrid.
    • Set Name to ordersByCity.
    • Set Value to ${result}.
  7. Set the Data property of the DataGrid to ${ordersByCity}.
  8. Click Autogenerate to generate the columns of the DataGrid.

If you run the application you should see the following in your browser:

Execute Stored Procedure

Add custom method to the partial class similar to previous chapter and invoke it when needed.

   [Inject]
   YourDbContext Context { get; set; }
   
   public async Task<int> UspUpdateEmployeeHireInfos(int? someID, string someOtherParam)
   {
      SqlParameter[] @params =
      {
         new SqlParameter("@returnVal", SqlDbType.Int) {Direction = ParameterDirection.Output},
         new SqlParameter("@someID", SqlDbType.Int) {Direction = ParameterDirection.Input, Value = someID},
         new SqlParameter("@someOtherParam", SqlDbType.VarChar) {Direction = ParameterDirection.Input, Value = someOtherParam}
      };

      Context.Database.ExecuteSqlRaw("EXEC @returnVal=[YourSPSchema].[YourSP] @someID, @someOtherParam", @params);

      int result = Convert.ToInt32(@params[0].Value);

      return await Task.FromResult(result);
   }