Need some help. New to Razor Components. I have a Razor Page that hosts an invoice, a subsection of which is payments . I created a Razor component for handling payments and updating a property called CurrentModel. I would like to return the changes made to the Razor Page that instantiated the Razor component. I thought I could do this by setting the component param to the method (based on https://learn.microsoft.com/en-us/aspnet/core/blazor/components/event-handling?view=aspnetcore-9.0#eventcallback).
Component:
[Parameter]
public EventCallback<List<Partial>> TestCallBack { get; set; }
Then later, in the component:
private async Task SetAmount(ChangeEventArgs e, int paymentId)
{
var amount = e.Value.ToDecimal();
if (amount.HasValue)
{
CurrentModel = CurrentModel.SetAmount(paymentId, amount.Value, Validator);
}
await TestCallBack.InvokeAsync(CurrentModel);
}
Component declaration in the Razor Page:
<component type="typeof(Components.Invoices.Payments)" render-mode="ServerPrerendered" param-testcallback="@Model.ReturnCallBack" />
(also tried)
<component type="typeof(Components.Invoices.Payments)" render-mode="ServerPrerendered" TestCallBack="@Model.ReturnCallBack" />
public async Task ReturnCallBack(List<Partial> partials)
{
...
}
Either way, VS tells me:
The answer is, of course, yes, I do wish to invoke said method, but I can't figure out to get this to fire all the way through. Seems the above is nullifying the delegation.
Is my approach not the standard way of doing this? Is there another approach I should follow?
I expected the approach to work, but something is preventing delegation.
From my understanding you want to call a method(return result) in razor pages from a blazor component. You could use httpclient and send the paramethers as json to do it.
Payments.razor
@inject HttpClient Http
<InputText @onchange="e=>SetAmount(e,2)">Call Razor Pages Method</InputText>
@code {
private async Task SetAmount(ChangeEventArgs e, int paymentId)
{
...
var json = JsonSerializer.Serialize(CurrentModel);
var response = await Http.GetAsync($"Index?handler=ReturnCallBack&serilizedPartials={json}");
...handle the response
}
}
Razor view (Index.cshtml)
<component type="typeof(Payments)" render-mode="ServerPrerendered" />
Index.cshtml.cs
public IActionResult OnGetReturnCallBack(string serilizedPartials)
{
var partials = JsonSerializer.Deserialize<List<Partial>>(serilizedPartials);
return new JsonResult(new { message = "Test method called!" });
}
Don't forget to add baseaddress
builder.Services.AddScoped(sp => new HttpClient
{
BaseAddress = new Uri("https://localhost:7257/")
});