(11/30) Let's learn Blazor together: Arbitral attributes

(11/30) Let's learn Blazor together: Arbitral attributes

Currently, MyButton has 3 [Parameters]. If you add them, a new [Parameter] will have to be defined. In order to avoid constantly updating this Component, we use the '@attribute' provided by Blazor.

最后更新 12/15/2021 10:53 PM
StrayaWorker
预计阅读 3 分钟
分类
Blazor
专题
Learn the Blazor series together
标签
.NET C# ASP.NET Core Blazor

目前MyButton有 3 个[Parameter],如果再增加的话,又要再定义新的[Parameter],为了避免不断更新这个 Component,我们来用 Blazor 提供的@attribute

首先把原本的<button>改为<input>,在MyButton.razor定义一个带有[Parameter]InputAttributes,类型为Dictionary<string, object>,先给初始值,如果外部没有传入这个参数的话就会套用初始值。

接着在PostBase.razor.cs也定义一个同名变量,不过里面的valueclass有稍微改动。

最后Post.razor调用的MyButton只传入InputAttributes,这样就完成了。

不过好像哪里怪怪的,因为只用了一个变量InputAttributes,导致原本的 Reset 按钮跟 Submit 变得一样了,但如果再定义一个为 Reset 产生的变量,又跟原本一样麻烦了。

这时候就要用到[Parameter]的参数CaptureUnmatchedValues了,我们将原本的[Parameter]改成[Parameter(CaptureUnmatchedValues = true)]或是[Parameter(true)]也行,告诉 Blazor 这个变量会捕捉任何不符合InputAttributes中定义的值。

接着把PostBase.razor.cs的变量InputAttributes删除,因为不能再这样定义了,我们等一下来看看如果保留的话会有什么结果。

最后PostBase.razor随意给<MyButton>我们想要的 html 属性,就可以看到变回 Submit 跟 Reset 按钮了,要注意的是因为变成我们自由定义,所以没有了强类型的约束。

这时候有人可能会发现,两个<MyButton>有个相同 html 属性type,既然重复,可以定义在PostBase.razor.csInputAttributes吗?

可惜错误信息告诉我们:如果用了CaptureUnmatchedValues就不能明确定义InputAttributes了,所以使用的人须特别注意这点。

还有一点是 html 属性的读取顺序是由右到左,若有重复的 html 属性,右边的会覆盖左边的,我们在MyButton.razor@attribute右边加上value="MyButton",打开网页可以看到两颗按钮都变成 Mybutton 了,所以若要给初始值的话,最好是放在@attribute左边,以免覆盖传进来的值。

** Quotes: **

  1. Blazor Attribute Splatting
  2. Ref: Arbitrary attributes and parameters in Blazor

** Note: The code in this article is refactored through. NET 6 + Visual Studio 2022. You can click on the original link to compare and learn the refactored code. Thank you for reading and support the original author **

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 12/25/2021

(29/30) Everyone learn Blazor together: Blazor unit testing

Probably the most boring process of developing a system is to solve bugs, especially the error of trying to value null objects (`Object reference not set to an instance of an object.`). This should be the most common problem that most people encounter when they first step into the programming field. In order to relieve themselves from the boring process of solving bugs, this article introduces 'unit testing'.

继续阅读
同分类 / 同标签 12/25/2021

(28/30) Everyone learns Blazor together: Policy-based authorization

It was mentioned before that 'ASP.NET Core Identity' uses 'Claim' based authentication. In fact,'ASP.NET Core Identity' has different types of authorization methods, the simplest are 'login authorization','role authorization', and 'Claim authorization', but all of the above are implemented in one way: 'Policy-based authorization'.

继续阅读