Simple binding in Blazor

September 24, 2019

A while back, I asked on Dev about moving my blog from Wordpress to … well, not Wordpress anymore. My main critera was to Markdown instead of whatever the Wordpress format is called. The main issue being that you need to replace the code tags.

I resolved to create a tool to do it for me. I’m doing so in Blazor.

The first task was to create a very simple data binding scenario, so I could handle all the view logic in the View Model. I’ve previously written about using view models. This post covers the scenario where you want to bind text boxes and a button.

Let’s see the View Model first:



    public class MainViewModel
    {
        public string WpText { get; set; }
        public string MdText { get; set; }

        public void ConvertText()
        {
            MdText = $"Converted {WpText}";
        }
    }

Okay, so we have two strings, and a method that populates the second string with the first. As per the linked post, the plumbing for the view model is very simple; first, it’s registered in ConfigureServices:




        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<MainViewModel, MainViewModel>();
        }

Then it’s injected into the Razor view:



@page "/"
@inject ViewModels.MainViewModel MainViewModel

In fact, the next part is much simpler than I thought it would be. To bind a view model property to the view, you just use the syntax bind:

[code lang=“html”]

    <div class="form-group col-md-6">
        <label for="MdText">Markdown</label>
        <input type="text" @[email protected] class="form-control" id="MdText" name="MdText"/>
    </div>
</div>
<div class="row">
    <div class="form-group col-md-12">
        <input type="button" value="Convert" @onclick=@(() => MainViewModel.ConvertText()) class="form-control" id="Submit" />
    </div>
</div>



Just to point out one thing that tripped me up before I leave this: the event handlers that relate to Blazor must be prefixed with an at symbol (@).

# References

[https://www.nativoplus.studio/blog/blazor-data-binding-2/](https://www.nativoplus.studio/blog/blazor-data-binding-2/)


Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024