MudBlazor TextChanged Data Conversion

28 views Asked by At

I am creating a dynamic form with MudBlazor in order to edit an object. This object has various datatypes. I have no issues creating the form and loading the data using @bind-Value. However, when the values are changed, only the "string" datatype works as expected, all others don't. Investigating the "TextChanged" callback for MudBlazor, I discovered it is a string type and that explains why only that datatype updated.

I have also tried to use the "ValueChanged". However, this does display the data with its elements.

Is there a way for me to accomplish this by maybe converting the "TextChanged" to the specific datatype? Is there any way I may accomplish the results I am looking for in any other form?

 @if (property.PropertyType == typeof(string))
 {
     var stringValue = (string)value;
     <MudTextField T="string" @bind-Value="stringValue" Label="@propertyName" 
         TextChanged="value => property.SetValue(objectToEdit, value)"
         Variant="MudBlazor.Variant.Outlined" AdornmentColor="Color.Warning" 
         Immediate="true" />
   }
 }
 else if (property.PropertyType == typeof(DateTime) || property.PropertyType == 
 typeof(DateTime?))
 {
      var dateValue = (DateTime?)(value ?? default(DateTime?));
      <MudTextField T="DateTime?" @bind-Value="dateValue" Format="yyyy-MM-dd" 
               InputType="InputType.Date" Label="@propertyName" 
               TextChanged="dateValue => property.SetValue(objectToEdit, value)"                                                                           
               Variant="MudBlazor.Variant.Outlined" 
               AdornmentColor="Color.Warning"  Immediate="true" />
 }
 else if (property.PropertyType == typeof(int?))
 {
         var intValueNull = (int?)value;
         <MudTextField T="int?" @bind-Value="intValueNull" Label="@propertyName" 
         Variant="MudBlazor.Variant.Outlined"
               TextChanged="intValueNull => property.SetValue(objectToEdit, value)" 
               AdornmentColor="Color.Warning" Immediate="true" />
 }
 else if (property.PropertyType == typeof(short?))
 {
       var shortValueNull = (short?)value;
       <MudTextField T="short?" @bind-Value="shortValueNull" Label="@propertyName" 
       Variant="MudBlazor.Variant.Outlined"
       TextChanged="shortValueNull => property.SetValue(objectToEdit, value)"
       AdornmentColor="Color.Warning" Immediate="true" />
 }
1

There are 1 answers

0
1moreLearner On

For future reference and if someone decide to use this piece of code.

The solution was this:

TextChanged="intValue => {
    if (!string.IsNullOrEmpty(intValue.ToString())) { 
       property.SetValue(objectToEdit, int.Parse(intValue)); 
       } 
    }"