So, I think this blog (.NET Talk) will become a daily
code journal of sorts. Anyways…
Today, I built a simple Blazor Server app that takes in input via forms for People and Addresses. I added two Razor Components and two models to the default code.
PersonModel.cs & AddressModel.cs
I quickly converted both of these to have file-scoped namespaces (more horizontal space is always nice). These are not complicated models. I could have added more data annotations to keep the data a certain length, but the point of today’s exercise was for me to really get how form data moves and how to use models with forms to send data. Below are screenshots from both files.
The Pages Components
Though these may seem like pages, they are actually
components. I added the @page directive to make them routable. However, because
they are components, you can use them within the index razor page. Pretty
nifty.
Anyways, both pages work more or less the same. There is an
EditForm in both files that contains Data Annotation Validators that will check
to make sure what is input matches the model. We also have a Validation Summary
that will show a list of Validation messages at the top. The @bind-Value is the
really important part. This is what binds the data to the instantiated model
that we can then send to wherever. In our case, it is a List of type PersonModel
that we will loop over later (seen in the unordered list: ul). This will let us
show our data on screen once we have a (valid) submit.
This kind of stuff (the models and data flow) took me awhile to get my head wrapped around, but once you do it enough times, you will “see it.” An easy practice for today, but it’s great to keep things fresh! Below are screenshots from both files.