This is a migrated thread and some comments may be shown as answers.

Fill a DropDownList from a model

4 Answers 1127 Views
DropDownList
This is a migrated thread and some comments may be shown as answers.
Javier
Top achievements
Rank 2
Veteran
Javier asked on 23 Nov 2020, 05:03 PM

Good Morning.
I am trying to fill a DropDownList from a model. The model is as follows:

    public class StatusEnvioModel
    {
        public string Code{ get; set; }
        public string Description { get; set; }
    } 

 

Then I create a List as follows:

        public IEnumerable<StatusEnvioModel> ListaEstadosGuia = new List<StatusEnvioModel>()
        {
            new StatusEnvioModel {Code = "REP", Description = "Recogida en punto de venta" },
            new StatusEnvioModel {Code = "RED", Description = "Envio recogido en domicilio" },
            new StatusEnvioModel {Code = "IAC", Description = "Ingreso a Cedi" },
            new StatusEnvioModel {Code = "RUT", Description = "En distribución" },
            new StatusEnvioModel {Code = "SAD", Description = "Salida ciudad destino" },
            new StatusEnvioModel {Code = "LTH", Description = "En transito" },
            new StatusEnvioModel {Code = "IFE", Description = "Intento fallido de entrega" },
            new StatusEnvioModel {Codigo = "ENT", Description = "Entregado" },
            new StatusEnvioModel {Code = "IFP", Description = "Intento fallido de entrega en punto Venta" },
            new StatusEnvioModel {Code  = "EPV", Description = "Entregado en punto de venta" }
        };

And then in the code define and initialize a property as follows:

        protected List<StatusEnvioModel> EstatusGuia { get; set; } = new List<StatusEnvioModel>();


        protected override async Task OnInitializedAsync()
        {
            EstatusGuia = AppData.ListaEstadosGuia.ToList<StatusEnvioModel>();
        }

And in the page I put a DropDownList in the following way:

        <div class="form-group">
            <label for="TipoStatusDDL">
                <span>Estatus guías <span class="k-required">*</span></span>
            </label>
            <TelerikDropDownList Id="TipoStatusDDL" Data="@EstatusGuia" TItem="Codigo" TValue="Descripcion"
                                 Width="100%" PopupWidth="400px" DefaultText="Seleccione un estatus de guía" />
        </div>

The problem is that I get an error in Data = "@ EstadusGuia" TItem = "Code" and TValue = "Description"

What is the problem?

Thank you.

 


4 Answers, 1 is accepted

Sort by
0
Nadezhda Tacheva
Telerik team
answered on 26 Nov 2020, 03:04 PM

Hi Javier,

TItem and TValue parameters are used when you cannot provide Value or Data or both when the component initializes (more details you can find here).

The error you are getting is due to the following reasons:

  • TItem specifies the type of the model to which the component is bound, it determines the type of the reference object. You have defined it as TItem="Codigo" and the correct TItem for your case is "StatusEnvioModel" as this is actually the type of the items in you collection

  • TValue shows the type of the value field from the model to which the component is bound. You have set it to TValue="Descripcion". However, the correct TValue in this case is "string". This is the type of the ValueField that the component is bound to ("Code")

OnInitialized method is invoked when the component initializes. When you are getting the data in it, basically you are loading the data the moment the component renders.

Therefore, since you already have the data and the value, you don't need to specify TItem and TValue. You need TextField and ValueField properties to point to the corresponding names of the model (more details you can find here).

I have created the following example using your dropdown setting to illustrate the component behavior:

 

Selected value: @selectedValue

<div class="form-group">
    <label for="TipoStatusDDL">
        <span>Estatus guías <span class="text-danger">*</span></span>
    </label>
    <TelerikDropDownList Id="TipoStatusDDL" Data="@ListaEstadosGuia" ValueField="Code" TextField="Description"
                         @bind-Value="selectedValue"
                         Width="100%" PopupWidth="400px" DefaultText="Seleccione un estatus de guía" />
</div>

@code{
    //Acts as a unique identifier for the value selected in the dropdown. Can be used further where needed
    public string selectedValue { get; set; }

    //Usually you would have the model in a separate file
    public class StatusEnvioModel
    {
        public string Code { get; set; }
        public string Description { get; set; }
    }

    //defining the collection field in the view-model
    public IEnumerable<StatusEnvioModel> ListaEstadosGuia { get; set; }

    //populating the data in ListaEstadosGuia when OnInitialized is invoked
    protected override async Task OnInitializedAsync()
    {
        await Task.Delay(2000);
        ListaEstadosGuia = new List<StatusEnvioModel>()
        {
            new StatusEnvioModel {Code = "REP", Description = "Recogida en punto de venta" },
            new StatusEnvioModel {Code = "RED", Description = "Envio recogido en domicilio" },
            new StatusEnvioModel {Code = "IAC", Description = "Ingreso a Cedi" },
            new StatusEnvioModel {Code = "RUT", Description = "En distribución" },
            new StatusEnvioModel {Code = "SAD", Description = "Salida ciudad destino" },
            new StatusEnvioModel {Code = "LTH", Description = "En transito" },
            new StatusEnvioModel {Code = "IFE", Description = "Intento fallido de entrega" },
            new StatusEnvioModel {Code = "ENT", Description = "Entregado" },
            new StatusEnvioModel {Code = "IFP", Description = "Intento fallido de entrega en punto Venta" },
            new StatusEnvioModel {Code  = "EPV", Description = "Entregado en punto de venta" }
        };
    }
}

 

Note on the side that might be helpful:

  • The k-required class could work in a specifically defined Telerik form. I can see you are using Bootstrap form-group so for the current purpose of marking the label as required you can use the "text-danger" Bootstrap class as per the example I provided.

Regards,
Nadezhda
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

1
Javier
Top achievements
Rank 2
Veteran
answered on 19 Mar 2021, 12:17 PM

Hi, Nadezhda.

Definitely this solution does not work.Now I am trying to fill a DropDownList as follows, following your suggestion:

I have a List <IntegradorComboViewModel> where the IntegradorComboViewModel entity is composed of two properties:

public class IntegratorComboViewModel

{

public string Id {get; set; }

public string Name {get; set; }

}

And the DropDownList I configure it as follows:

<TelerikDropDownList Data = "@ integrators" TextField = "Name" ValueField = "Id" @ bind-Value = "@ client.PlataformaIntegracion" Id = "integradorDDL" Width = "100%" PopupWidth = "400px" DefaultText = "Select an integrator" />

And I get the following error:

Error CS0411 The type arguments for method 'TypeInference.CreateTelerikDropDownList_3<TItem, TValue>(RenderTreeBuilder, int, int, IEnumerable<TItem>, int, string, int, string, int, string, int, string, int, string, int, string, int, TValue, int, EventCallback<TValue>, int, Expression<Func<TValue>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

And I do not understand why. I followed his answer and also the recommended article https://docs.telerik.com/blazor-ui/components/dropdownlist/data-bind?&_ga=2.29320250.768445361.1616153756-200406228.1614622833#missing-value-or-data
but nothing works. This is very frustrating

Thanks,

 

Javier

 

0
Javier
Top achievements
Rank 2
Veteran
answered on 19 Mar 2021, 12:51 PM

Hi, Nadezhda.

Something similar is happening to me with the grid, I get the same error message, when I insert a grid on a page or a blazor control:

Error CS0411 The type arguments for method 'TypeInference.CreateTelerikGrid_0<TItem>(RenderTreeBuilder, int, int, IEnumerable<TItem>, int, string, int, GridFilterMode, int, bool, int, bool, int, int, int, bool, int, bool, int, bool, int, RenderFragment, int, RenderFragment, int, RenderFragment)' cannot be inferred from the usage. Try specifying the type arguments explicitly. Auropaq.SifaPickup.Client

And the grid is configured as follows:

<TelerikGrid Data="@Tracking" Height="400px" FilterMode="@GridFilterMode.FilterMenu"
             Sortable="true" Pageable="true" PageSize="20" Groupable="true" Resizable="true" Reorderable="true">
    <GridColumns>
        <GridColumn Field="Plataforma" Title="Plaraforma" Width="170px" />
        <GridColumn Field="NumeroDocumento" Title="Documento" Width="165px" Editable="false" Groupable="false">
        </GridColumn>
        <GridColumn Field="EstatusIntegrador" Title="Estatus Integrador" Width="120px" Editable="false" Groupable="true" />
        <GridColumn Field="EstatusProships" Title="Estatus Proships" Width="120px" Editable="false" Groupable="false" />
        <GridColumn Field="UrlIntegracion" Title="URL respuesta" Width="120px" Editable="false" Groupable="true" />
        <GridColumn Field="Comentario" Title="Comentarios" Width="110px" Editable="false" Groupable="false" />
    </GridColumns>
    <GridToolBar>
        <GridCommandButton Command="ExcelExport" Icon="@IconName.FileExcel">Exportar a Excel</GridCommandButton>
    </GridToolBar>
    <GridExport>
        <GridExcelExport FileName="Listado estustus integración" AllPages="true" />
    </GridExport>
</TelerikGrid>

0
Nadezhda Tacheva
Telerik team
answered on 24 Mar 2021, 07:04 AM

Hello Javier,

Please see my comments on the separate components as follows:

DropDownList

When setting the component properties, double check if there are any additional spaces left - that will cause errors with the syntax (for example there is a space between the "@" and the "integrators" in the Data parameter and the framework does not recognize it as razor syntax).

The model (IntegratorComboViewModel) is correctly defined, however normally the Id-s are of type int or guid. Such a setup (binding the DropDownList to a model) is useful when you have a numerical representation of a list (for example, the Id-s of the integrators), and you want the user to choose them based on a friendly text name (the integrators names).

So, you can also consider binding the DropDownList to primitive types such as strings (in your case the data could be a list of strings - the integrators and you will not need to define a model, just to pass a list of strings to the Data parameter of the component). 

I wasn't able to see the data generation in the snippet below but it could be something like this (copy and paste the snippet to test it).

<TelerikDropDownList Data="@integrators" TextField="Name" ValueField="Id"
                     @bind-Value="@selectedValue" Id="integradorDDL"
                     Width="100%" PopupWidth="400px" DefaultText="Select an integrator">
</TelerikDropDownList>

@code{
    int selectedValue { get; set; }

    public List<IntegratorComboViewModel> integrators = Enumerable.Range(1, 20).Select(x => new IntegratorComboViewModel
    {
        Name = "integrator " + x,
        Id = x
    }).ToList();

    public class IntegratorComboViewModel
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }
}

 

Note: The Value parameter gets/sets the value of the component, it can be used for binding. It should match the type of the field you are binding the ValueField to (for example if the ValueField="Id" and the Id is of type int, the Value parameter should be bound to a field also of type int). As per your current setup the Value is bound to client.PlataformaIntegracion which might be causing some issues. In order to verify that double check its type, does it match the type of the ValueField?  If this doesn't solve the issue, you can send us the reproduction code to investigate further. 

Grid

The setup of the Grid looks correct. In order to define the issue, could you also send us a runnable reproduction to see how the model is defined and the data  generated. 

Note: I noticed you are using IconName, however it is an obsolete class and you can see how to migrate from it in this knowledge base article.

Regards,
Nadezhda Tacheva
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Tags
DropDownList
Asked by
Javier
Top achievements
Rank 2
Veteran
Answers by
Nadezhda Tacheva
Telerik team
Javier
Top achievements
Rank 2
Veteran
Share this question
or