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.
- Add a new page to your Radzen application called
Sum
. - Open the
server\Pages\Sum.razor.cs
file in your your code editor of choice. - Add the following method to the empty
SumComponent
partial class.public int Sum(int x, int y) { return x + y; }
- Drag and drop a Button component in a Radzen page.
- 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
andy
parameters of theSum
method.
- 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? Theresult
keyword is a placeholder which means “the result of the current custom method”. Thensum
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:
- When you click the button the event handler executes the custom
Sum
method with parametersx=1
andy=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.
- Create two page properties -
x
andy
. They will store the user input and be the arguments of theSum
method. - Drag and drop two Numeric components. Data-bind the first component to
x
and the second toy
. - Edit the Click event handler of the button from the previous section. Set the
x
parameter to${x}
and they
parameter to${y}
. This will use the values of thex
andy
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.
- Add a new MSSQL data source for the Northwind database. You can check the MSSQL help topic for additional instructions.
- Add a new empty page
Orders
to your application. - Open the
server\Pages\Orders.razor.cs
file with your code editor. - Inject the Entity Framework context created for the Northwind database as a property decorated with the
Inject
attribute.[Inject] NorthwindContext NorthwindContext { get; set; }
- 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:
- Create a new page in your application.
- Drag and drop a TextBox and a Button.
- Create a page property called
country
and data-bind the TextBox to that property. - 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}
.
- 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.
- Make sure you have a MSSQL data source for the Northwind database.
- Add a new class in the
Orders.razor.cs
file.public class OrderByCity { public string ShipCity { get; set; } public int Count { get; set; } }
- Add a new method to the
OrdersComponent
partial classpublic IEnumerable<OrderByCity> OrdersByCity() { var orders = NorthwindContext.Orders.GroupBy(o => o.ShipCity) .Select(group => new OrderByCity() { ShipCity = group.Key, Count = group.Count() }); return orders; }
- Drag and drop a DataGrid component.
- Add a new event handler for the Page Load event.
- Set Type to Invoke method
- Pick the OrdersByCity method.
- 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}
.
- Set Type to Set property. We want to store the result of the
- Set the Data property of the DataGrid to
${ordersByCity}
. - 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);
}