Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MatBlazor select issue

my code should be like this, but it's getting null reference exception

 <MatSelect Label="Atık Tipi" @bind-Value="@SecilenAtikGrubu.GrupId" Style="width:100%">
      @foreach (var item in TumAtikTipleri)
     {
        <MatOption Value="@item.Id">@item.Deger1</MatOption>
     }
 </MatSelect>

but when i use like this, it is working

  <select class="mdc-select__native-control" @bind="SecilenAtikGrubu.GrupId">
     @foreach (var item in TumAtikTipleri)
     {
         <option value="@item.Id">@item.Deger1</option>
     }
  </select>

Binding value class is like below (SecilenAtikGrubu and TumAtikTipleri)

 public class GrupKodlari : KayitBilgisi
{
    [Key]
    public int Id { get; set; }
    public string Tur { get; set; }
    public string Isim { get; set; }
    public string Deger1 { get; set; }
    public string Deger2 { get; set; }
    public string Deger3 { get; set; }
    public int? GrupId { get; set; } 
    public virtual GrupKodlari Grup { get; set; }

}
like image 293
lkmcelik Avatar asked Mar 03 '23 00:03

lkmcelik


2 Answers

The bad news are that, I have checked it and, MatSelect is unable to be binded to a nullable type.

Now the good news, first one, you can use an auxiliary property as a workaround, Try it at blazorfiddle.

public int GrupIdAux
{
    set{
        GrupId = (value==0?(int?)null:value);
    }
    get {
        return (GrupId==null?0:GrupId.Value);
    }
}

just a sample of the mat select

Second good new: MatBlazor is an opensource project. If you need to work with nullable types you can improve MatSelect control and send a PR. The project owner is open to contributions (for example I wrote NumericUpDown) If you can't improve component, you can pay someone to write it for you or you can post a request for the new feature on project issues. It looks like good idea, would be wonderful to bind nullable objects.

like image 183
dani herrera Avatar answered Mar 28 '23 17:03

dani herrera


@daniherrera You can bind MatSelect to a nullable type. However you have to specify that you accept a nullable type with ?. Example:

<MatSelect Label="Pick a Food Group" @bind-Value="@guidValue">
    <MatOption TValue="Guid?" Value="@(null)"></MatOption>
    <MatOption TValue="Guid?" Value="@(new Guid("20A82054-F493-4C7B-81A4-4F9A1EDD7C2E"))">Bread, Cereal, Rice, and Pasta</MatOption>
    <MatOption TValue="Guid?" Value="@(new Guid("4451642D-24F7-418F-8741-BA5089A1CC65"))">Vegetables</MatOption>
    <MatOption TValue="Guid?" Value="@(new Guid("5717DBBE-C205-4E33-9E07-892A51F64021"))">Fruit</MatOption>
</MatSelect>

<span>@guidValue</span>

@code
{
    Guid? guidValue = new Guid("20A82054-F493-4C7B-81A4-4F9A1EDD7C2E");
}

https://www.matblazor.com/Select#MatSelectGuid

Use int? Id and mark your MatOption with TValue="int?".

like image 27
Ogglas Avatar answered Mar 28 '23 16:03

Ogglas