1

I'm doing some testing with Blazor and wanted to take a string and simply change it to uppercase as follows:

@page "/InputBindingTest"
<h1>Binding examples...</h1>
<hr />

<h2>Text input example:</h2>
<p>Firing the 'oninput' event for each key press</p>

<input type="text" bind-value-oninput="@CurrentText" />

<p>Current value is: @CurrentText</p>

<p>Here it is again in UPPERCASE: @CurrentText.ToUpper()</p>

<h2>Checkbox example:</h2>
<input name="check1" type="checkbox" bind-value-onchange="@CurrentSetting" />
<label for="check1">@CurrentSetting</label>

@functions {
    private string CurrentText { get; set; }
    private bool CurrentSetting { get; set; }
}

Everything works except the ToUpper method on the string. Web Assembly takes a nasty dive:

WASM: Unhandled exception rendering component

I suppose this can't be done (yet) or am I doing something wrong?

Jason Shave
  • 2,462
  • 2
  • 29
  • 47

1 Answers1

4

A careful look at the generated error trace reveals this is about a null reference exception.

The simple fix is a ?. :

<p>Here it is again in UPPERCASE: @CurrentText?.ToUpper()</p>

and/or

private string CurrentText { get; set; } = "";

Blazor's binding can handle a null in @CurrentText</p> just fine.
But ToUpper() can't be called on a null string.

H H
  • 263,252
  • 30
  • 330
  • 514
  • see https://stackoverflow.com/questions/28352072/what-does-question-mark-and-dot-operator-mean-in-c-sharp-6-0 for the null conditional operator for the very useful ?. – Knox Jun 01 '19 at 13:00
  • Thanks @Henk. I forgot about that operator and didn't think to use it but it makes perfect sense in this case as we don't have any input to apply the method to. – Jason Shave Jun 01 '19 at 15:28