Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically binding input-text to class/object propertys using Blazor

Im trying to build a dynamic list of input field for properties inside a class using Blazor but cant figur out how to bind/link the content of a input box to a property of a class. (the class have can have a large number of public props, not only Name and Description as in the below example, they are not always of the type "string")

lets say that I have this class/model:

public class customer{
        public string Name { get; set; }
        public int Age { get; set; }
        public string Description { get; set; }

}

I got this blazor component (updateC.razor):

@inherits CLogic    
@if (nfo != null)
{
      @foreach (var obj in nfo)
      {
             <input type="text" class="form-control"      
             [email protected]().GetProperty(obj.ToString())/>
      }
}

and finally Clogic:

public class Clogic: ComponentBase{
    [Parameter]
    public Customer SCustomer { get; set; } = new Customer();
    [Parameter]
    public PropertyInfo[] nfo { get; set; }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            nfo = SCustomer.GetType().GetProperties();
            StateHasChanged();
        }
    }
}

This is suppose to bind changes made in each input field to the correct property in the current instance of SCustomer (when input is made it is suppose to update the correct property of the class/object). This is not working, values inside of SCustomer are not changed after input are done. I'm guessing that i'm going about this completely wrong but can't seem to figure out how to make this work and can't find any examples doing this.

like image 756
user10483669 Avatar asked Feb 20 '20 15:02

user10483669


2 Answers

@foreach (var propertyInfo in nfo)
{
    <input type="text" class="form-control"      
    value="@propertyInfo.GetValue(SCustomer)" 
    @onchange="@((ChangeEventArgs __e) =>
       propertyInfo.SetValue(SCustomer, __e.Value.ToString()))" />
}
like image 124
agua from mars Avatar answered Sep 27 '22 02:09

agua from mars


@foreach(propertyInfo in nfo)
{
  <label>@propertyInfo.Name</label>
  <input type="text" value="@propertyInfo.GetValue(SCustomer)" @onchange="@((ChangeEventArgs __e) => 
    propertyInfo.SetValue(SCustomer,Convert.ChangeType(__e.Value, 
    propertyInfo.PropertyType,null))"/>
}
like image 30
Biju Kalanjoor Avatar answered Sep 23 '22 02:09

Biju Kalanjoor