What is the [Parameter] Attribute in c# - c#

I was watching a tutorial in Blazor. Then I came across this code and I can't seem to find it in the Internet or I think I'm not using the right terms for searching atleast.
#code{
[Parameter]
public IList<Todo> Todo {get; set;}
}
Is it only exclusive in blazor or it is available in c#.
Kindly give some references. Thanks in advance.

This is explained in Create and use ASP.NET Core Razor components, specifically in the Component Parameters section.
[Parameter] is used to mark the component parameters that can be set when the component is used in another page. Borrowing from the doc example this component doesn't have any parameters :
<div class="panel panel-default">
<div class="panel-heading">#Title</div>
<div class="panel-body">#ChildContent</div>
<button class="btn btn-primary" #onclick="OnClick">
Trigger a Parent component method
</button>
</div>
#code {
public string Title { get; set; }
public RenderFragment ChildContent { get; set; }
public EventCallback<MouseEventArgs> OnClick { get; set; }
}
Without the [Parameter] attribute, those are just public properties that can't be set from other pages. The following line would be invalid :
<ChildComponent Title="Panel Title from Parent" />
While this :
<div class="panel panel-default">
<div class="panel-heading">#Title</div>
<div class="panel-body">#ChildContent</div>
<button class="btn btn-primary" #onclick="OnClick">
Trigger a Parent component method
</button>
</div>
#code {
[Parameter]
public string Title { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public EventCallback<MouseEventArgs> OnClick { get; set; }
}
Allows us to set the parameters whenever we use that component :
<ChildComponent Title="Panel Title from Parent"
OnClick="#ShowMessage">
Content of the child component is supplied
by the parent component.
</ChildComponent>

All attributes in C# have to reference a type defining that attribute somewhere. That Blazor code is still C#.
In this case, I believe it it refers to Microsoft.AspNetCore.Components.ParameterAttribute - the documentation is currently MIA, but that may well improve over time. There's more detail in the Blazor documentation.
In general, if you have the code in front of you (generally a good idea when watching a tutorial, if at all possible) you can hover over the attribute in Visual Studio to see its fully qualified name or navigate to it.

Related

How to properly enable the bind* syntax in Blazor for custom components?

I'm developing a UI library on top of Blazor and I like to enable the bind* syntax for my components so consumers could use it too.
Context
I've read and seen plenty of examples so on the most basic level let's say we have the following custom component named RawCustomInput.razor:
<input type="text" value="#Value" #onchange="OnValueChanged" style="width: 5rem" />
#code {
[Parameter]
public string? Value { get; set; }
[Parameter]
public EventCallback<string> ValueChanged { get; set; }
private async Task OnValueChanged(ChangeEventArgs args)
=> await ValueChanged.InvokeAsync(args.Value as string);
}
And another component that consumes it named InputPage.razor like this:
#page "/input"
<PageTitle>InputPage</PageTitle>
<RawCustomInput
#bind-Value="#_name" />
#if (!string.IsNullOrEmpty(_name))
{
<p>#_name</p>
}
#code {
private string? _name = null;
}
Problem
Now, the above works but say I want to change the event from onchange to oninput on the consumer side? so I tried to do something like this #bind-Value:event="oninput" but then I get the following error:
does not have a property matching the name 'oninput'
So I thought I could solve this by introducing #oninput="OnValueChanged" to RawCustomInput.razor which looks like this:
<input type="text" value="#Value" #onchange="OnValueChanged" #oninput="OnValueChanged" style="width: 5rem" />
#code {
[Parameter]
public string? Value { get; set; }
[Parameter]
public EventCallback<string> ValueChanged { get; set; }
private async Task OnValueChanged(ChangeEventArgs args)
=> await ValueChanged.InvokeAsync(args.Value as string);
}
But this didn't work so I read the error again and realized that something like #bind-Value:event="ValueChanged" might work and it worked! so what I did is add another property that looks like this:
[Parameter]
public EventCallback<string> ValueChanging { get; set; }
So now my RawCustomInput.razor looks like this:
<input type="text" value="#Value" #onchange="OnChange" #oninput="OnInput" style="width: 5rem" />
#code {
[Parameter]
public string? Value { get; set; }
[Parameter]
public EventCallback<string> ValueChanged { get; set; }
[Parameter]
public EventCallback<string> ValueChanging { get; set; }
private async Task OnChange(ChangeEventArgs args)
=> await ValueChanged.InvokeAsync(args.Value as string);
private async Task OnInput(ChangeEventArgs args)
=> await ValueChanging.InvokeAsync(args.Value as string);
}
And finally I could use the syntax below that worked too which is great but raises few questions.
<RawCustomInput
#bind-Value="#_name"
#bind-Value:event="ValueChanging" />
Questions
It's possible to use the syntax bind-{Property}="{Expression}" for binding but is it possible to enable this syntax bind="{Expression}" on custom components? because when I'm trying to do something like this <RawCustomInput #bind="#_name" /> it throws with the following error does not have a property matching the name '#bind' but this <input type="text" #bind="#_name" /> works, why?
It's possible to do <input type="text" #bind="#_name" #bind:event="oninput" /> but doing <RawCustomInput #bind-Value="#_name" #bind-Value:event="oninput" /> throws with the following error does not have a property matching the name 'oninput', why? to achieve a similar thing I have to introduce additional property as I pointed above but then it's seems a bit odd that for bind:event I need to provide the name of the event whereas for bind-{Property}:event I need to pass a property which might makes sense but I'm not sure I understand the reason.
First you need to understand the difference between components and elements.
<input type="text" value="#Value" .. is an element declaration. It's html code.
<RawCustomInput #bind-Value="#_name" /> is a component declaration.
Second, you are defining stuff in the Razor language, not true C#. #bind and #bind-value are directives to the Razor compiler, and are handled differently.
The #bind is used to bind elements. It gets compiled by the Razor compiler into C# code like this:
__builder.AddAttribute(19, "value", BindConverter.FormatValue(this.surName));
__builder.AddAttribute(20, "onchange", EventCallback.Factory.CreateBinder(this, __value => this.surName = __value, this.surName));
Note that it uses various factory classes to build the "getter" to provide a correctly formatted string to the input value and a "setter" to handle the generated onchange event from the input to update the variable.
In comparison, this is the code for the component #bind-value on a component
__builder.AddAttribute(11, "Value", RuntimeHelpers.TypeCheck<String>(this.firstName));
__builder.AddAttribute(12, "ValueChanged", RuntimeHelpers.TypeCheck<EventCallback<String>>(EventCallback.Factory.Create<String>(this, RuntimeHelpers.CreateInferredEventCallback(this, __value => this.firstName = __value, this.firstName))));
It's setting the value of the Parameter Value and creating an anonymous function to set the value from the eventcallback ValueChanged. There is no direct wiring into the underlying input element declared within the component. It's setting the component parameter and sinking the component event. How they are wired up is up to you the designer.
To demonstrate, here's a very different component wiring for a "checkbox":
<button class="#this.ButtonCss" #onclick=this.OnValueChanged>#this.ButtonText</button>
#code {
[Parameter] public bool Value { get; set; }
[Parameter] public EventCallback<bool> ValueChanged { get; set; }
private string ButtonCss => Value ? "btn btn-success": "btn btn-danger";
private string ButtonText => Value ? "Enabled" : "Disabled";
private async Task OnValueChanged()
=> await ValueChanged.InvokeAsync(!this.Value);
}
When you declare your components as Razor Components you are restricted by the Razor language. For 99% of components this is Ok. But, if you want to do more exotic stuff, you need to drop back to writing your component directly as a C# class.
This shows one way of handling onchange/oninput.
#if(this.ChangeOnInput)
{
<input type="text" value="#Value" #oninput="OnValueChanged" class="form-control" />
}
else
{
<input type="text" value="#Value" #onchange="OnValueChanged" class="form-control" />
}
#code {
[Parameter] public string? Value { get; set; }
[Parameter] public bool ChangeOnInput { get; set; }
[Parameter] public EventCallback<string> ValueChanged { get; set; }
private async Task OnValueChanged(ChangeEventArgs args)
=> await ValueChanged.InvokeAsync(args.Value as string);
}

Inherit methods from component in Blazor

I have a modal component in Blazor that I am attempting to make more reusable. The modal has a base class which implements methods for Showing/Hiding the modal, and callbacks for Show and Hide.
public class Modalbase : ComponentBase
{
[Parameter] public RenderFragment ChildContent { get; set; }
[Parameter] public Action? Closed { get; set; }
[Parameter] public Action? Opened { get; set; }
protected bool show;
// ANCHOR - public methods
public void Hide()
{
show = false;
Closed?.Invoke();
this.StateHasChanged();
}
public void Show()
{
show = true;
Opened?.Invoke();
this.StateHasChanged();
}
}
For the razor implementation, I have a very simple component which provides the markup and renders content provided. This is in Modal.razor:
#inherits Modalbase
#if (this.show)
{
<div class='modal-container #(this.show ? "show" : "hidden")'>
<div class="overlay" #onclick="Hide" style="cursor:pointer;"></div>
<div class='modal'>
<div id="close-container" #onclick="Hide">
<div class="close"><i class="fa-solid fa-x fa-md"></i></div>
</div>
#this.ChildContent
</div>
</div>
}
which is then used like this:
<Modal #ref="modalRef">
<div>childcontent here</div>
</Modal>
#code {
Modal modalRef;
public void Show()
{
modalRef.Show();
}
}
The problem with this is that across many implementations of Modals, I have to keep implementing the Show and Hide methods. Those methods are on the Modal component reference, and not in the reference to the implementation of Modal.
Is there a way with OOP to have these methods available directly on the implementation of the Modal component, but also allow them to be overriden if something additional needs to be done before opening/closing the modal?
A workaround is just making modalRef public in implementations, and calling the methods directly from there. Like: childModal.modalRef.Show() But that feels like it could cause issues in cases where maybe I want to check if the user is logged in before showing the modal.

Blazor templating component with inheritance

I have a base component PetTemplate and a second PetDog that inherits and uses the template of PetTemplate. PetTemplate has a method named ToggleDisplay. My goal is when I click the button on the Index page that invokes the PetDog.ToggleDisplay method and show/hide the PetDog details on the page.
The "Inside" button in the sample code below works but "Outside" button don't. How can I invoke the ToggleDisplay method from a page or a parent component correctly?
Index.razor
#page "/"
<button #onclick="ShowPetDetails">Show Details (Outside)</button>
<PetDog #ref="dog" />
#code {
PetDog dog;
void ShowPetDetails()
{
dog.ToggleDisplay();
}
}
PetDog.razor
#inherits PetTemplate
<PetTemplate Name="Dog">
<div>Someone's best friend!</div>
</PetTemplate>
PetTemplate.razor
<div class="mt-3">
<button #onclick="ToggleDisplay">Show Details (Inside)</button>
<h3>Pet Name: #Name</h3>
<div style="display:#display">
#ChildContent
</div>
</div>
#code {
string display = "none";
[Parameter]
public string Name { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
public void ToggleDisplay()
{
display = display == "none" ? "block" : "none";
StateHasChanged();
}
}
When you use
<PetDog #ref="dog" />
#code {
PetDog dog;
void ShowPetDetails()
{
dog.ToggleDisplay();
}
}
You actually create a reference to the PetDog component, and then try to call a derived method, dog.ToggleDisplay(), on object you have no reference to ( the instance of the PetTemplate). In order to make it work, you'll have to get a reference to the parent component (PetTemplate), and provide it to the derived component (PetDog), like this:
PetTemplate.razor
<div class="mt-3">
<button #onclick="ToggleDisplay">Show Details (Inside)</button>
<h3>Pet Name: #Name</h3>
<div style="display:#display">
#ChildContent
</div>
</div>
#code {
string display = "none";
string val;
[Parameter]
public string Name { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
public void ToggleDisplay()
{
display = display == "none" ? "block" : "none";
InvokeAsync(() => StateHasChanged());
}
}
PetDog.razor
#inherits PetTemplate
<PetTemplate #ref="petTemplate" Name="Dog">
<div>Someone's best friend!</div>
</PetTemplate>
#code
{
PetTemplate petTemplate;
public PetTemplate PetTemplateProp { get; set; }
protected override void OnAfterRender(bool firstRender)
{
if(firstRender)
{
PetTemplateProp = petTemplate;
}
base.OnAfterRender(firstRender);
}
}
Index.razor
#page "/"
<button #onclick="ShowPetDetails">Show Details (Outside)</button>
<PetDog #ref="dog" />
#code {
PetDog dog;
void ShowPetDetails()
{
dog.PetTemplateProp.ToggleDisplay();
}
}
Note: Though Razor components are C# classes, you cannot treat them as normal classes. They behave differently. As for instance, you can't define a variable instance, and set its parameters, etc. outside of the component. At best, you can capture a reference to a component as well as call public methods on the component instance, as is done in the current sample. In short, component objects differ from normal classes.
It's also important to remember that each component is a separate island that can render independently of its parents and children.
But just wondering how can I change a component parameter value from outside of it, that inherited/uses a template. I tried the methods in the documentation or the resources I found, but it didn't work for my case
You should not (it was a warning) and probably cannot ( it may be now an error) change a component parameter's value outside of the component. As for instance, you can't capture a reference to a component and assign a value to its parameter property:
<PetTemplate #ref="petTemplate">
<div>Someone's best friend!</div>
</PetTemplate>
PetTemplate petTemplate;
This is not allowed: petTemplate.Name="Dog" as this is changing the parameter outside of its component. You can only do that like this:
<PetTemplate Name="Dog">
<div>Someone's best friend!</div>
</PetTemplate>
Furthermore, modification of a parameter property from within the component itself is deprecated ( currently you should get a warning, at least that is what Steve Sanderson suggested to the Blazor team).
To make it clear, you should not modify the parameter property Name from within the PetTemplate component. A parameter property should be automatic property; that is, having a get and set accessors like this: [Parameter] public string Name { get; set; }
And you should not use it like this:
private string name;
[Parameter]
public string Name
{
get => name;
set
{
if (name != value)
{
name = value;
// Code to a method or whatever to do something
}
}
}
This is deprecated as it may have side effects. Component parameters should be treated as DTO, and should not be modified. If you wish to perform some manipulation of the parameter value, then copy it to a local variable, and do your thing.
As pointed out by #enet Blazor component inheritance doesn't behave exactly as one would intuitively expect. This is a cleaner approach when you want to control a UI functionality that can be controlled both internally and externally:
Declare an event in the base component that is raised when the UI state is changed from within the component. Also let the variable that controls the state be a parameter. In you case, something like
PetTemplate.razor:
[Parameter]
public EventCallback OnToggleRequested {get;set;}
[Parameter]
public string Display {get;set;}
protected async Task RaiseToggle()
{
await OnToggleRequested.InvokeAsync();
}
In your PetDog, simple call the toggle method when inside click is raised
PetDog.razor:
<button #onclick="RaiseToggle">Show Details (Inside)</button>
In your container (in this case, index.razor) listen to the event and make changes. Also wire the outside button to the same method:
Index.razor:
<button #onclick="ToggleDisplay">Show Details (Outside)</button>
<PetDog OnToggleRequested="ToggleDisplay" Display="#display"/>
string display = "block";
void ToggleDisplay()
{
display = display == "none" ? "block" : "none";
}
Note that the event can be used at level of hierarchy and you don't need to capture any references anywhere.

How to two way bind a cascading value in Blazor?

I'm playing around with the custom template in Blazor and I'm trying to find to a way to two-way bind a CascadingValue or achieve something similar. Right now I have the following template.
#if (PopupVisible)
{
<DxPopup>
<HeaderTemplate>
<h4 class="modal-title">#HeaderText</h4>
<button type="button" class="close" #onclick="#UpdatePopupVisible">×</button>
</HeaderTemplate>
<ChildContent>
<div class="modal-body">
<div class="container-fluid">
#bodyContent
</div>
</div>
<div class="modal-footer">
#footerContent
<button class="btn btn-secondary" #onclick="UpdatePopupVisible">Cancel</button>
</div>
</ChildContent>
</DxPopup>
}
#code {
[CascadingParameter] public bool PopupVisible { get; set; }
[CascadingParameter] public EventCallback<bool> PopupVisibleChanged { get; set; }
[Parameter] public RenderFragment HeaderText { get; set; }
[Parameter] public RenderFragment footerContent { get; set; }
[Parameter] public RenderFragment bodyContent { get; set; }
private async Task UpdatePopupVisible()
{
PopupVisible = false;
await PopupVisibleChanged.InvokeAsync(PopupVisible);
}
}
Then I have a component that implements this template(child), and then I have that component called with a button press(parent). What I want to know is if there is a way to bind the PopupVisible parameter from the parent without having to bind it the child and having the child pass it to the template. I haven't found a way to two-way bind a cascading parameter but if possible I think that would be the best way to do so. Outside of that, I'm not sure if there is another way or I'm going to have to go with my current idea of passing the value.
You can't do two-way binding with cascading parameters. Cascading means flowing downstream, from parent to child, and not the other way around.
I'm not sure I understand your question...however, if you wish to pass a value from a parent component and back; you can do the following:
Note: This is a two-way Component data binding
Child Component
#code
{
private bool visible;
[Parameter]
public bool PopupVisible
{
get { return visible }
set
{
if (visible != value)
{
visible = value;
}
}
}
[Parameter] public EventCallback<bool> PopupVisibleChanged { get; set; }
// Invoke the EventCallback to update the parent component' private field visible with the new value.
private Task UpdatePopupVisible()
{
PopupVisible = false;
return PopupVisibleChanged.InvokeAsync(PopupVisible);
}
}
Usage
#page "/"
<DxPopup #bind-PopupVisible="visible" />
#code {
private bool visible;
}
Note: If you need some explanation, and believe that I did not answer your question, don't hesitate to tell me, but please take the time to phrase your questions... I could not completely understand questions.
what you can do is, Cascade the parent component and in the child component, access the parent Property you want to change like this:
Parent:
<CascadingValue Value="this">
<Child />
</CascadingValue>
Child:
[CascadingParameter]
public Parent Parent { get; set; }
.....
private void ChangeParentProperty()
{
Parent.Property = ....;
}
Any doubt feel free to ask.

Cant find MouseEventArgs

I have been following along with Create and use ASP.NET Core Razor components
I am having an issue with this section
<div class="panel panel-default">
<div class="panel-heading">#Title</div>
<div class="panel-body">#ChildContent</div>
<button class="btn btn-primary" #onclick="OnClick">
Trigger a Parent component method
</button>
</div>
#code {
[Parameter]
public string Title { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public EventCallback<MouseEventArgs> OnClick { get; set; }
}
I keep getting the following error
Severity Code Description Project File Line Suppression State
Error CS0246 The type or namespace name 'MouseEventArgs' could not be found (are you missing a using directive or an assembly reference?) BlazorList D:\Development\BlazorApp1\BlazorList\Pages\ShowListComponent.razor 19 Active
The event names have been changed in Preview 9
from the blog (https://devblogs.microsoft.com/aspnet/asp-net-core-and-blazor-updates-in-net-core-3-0-preview-9/):
Replace Microsoft.AspNetCore.Components.UIEventArgs with
System.EventArgs and remove the “UI” prefix from all EventArgs derived
types (UIChangeEventArgs -> ChangeEventArgs, etc.).
So preview 8 and below need the UI prefix on the event name and the Microsoft.AspNetCore.Components.UIEventArgs namespace.
preview 9 does not need the UI prefix on the event name. and requires the namespace System.EventArgs

Categories