Telerik Forums
UI for ASP.NET Core Forum
1 answer
11 views

I am trying to create a grid with 4 columns: Field, Operator, Value and a Delete button

The Field column is selectable from a drop down when editing and this I have done using a Action call.

The second column, Operator has a fixed set of operators like '>', '<', '>='. I was hoping to create this list right inside this grid definition. So I chose the overload: columns.ForeignKey(memberName, SelectList) and I have created a SelectList in the second argument. But it does not work and the Operator column is not showing a drop down:

@(
Html.Kendo().Grid<formFilter>()
	.Name("gridFilter")
	.ToolBar(toolbar =>
	{
		toolbar.Create().Text("Add");
		toolbar.Save().Text("Save").CancelText("Cancel");
	})
	.Editable(editable => editable.Mode(GridEditMode.InCell))
	.Columns(columns =>
	{
	columns.ForeignKey(c => c.filterName, ds => ds.Read(r => r.Action("fieldNames", "View1", new { className = "View1" })), "filterName", "filterName").Title("Field").Width(200);
	columns.ForeignKey(c => c.filterEval, new SelectList(
		new List<SelectListItem>
			{
				new SelectListItem { Text = ">", Value = ">"},
				new SelectListItem { Text = "<", Value = "<"},
				new SelectListItem { Text = ">=", Value = ">="},
			}, "Value", "Text"))
		.Title("Operator").Width(200);
	columns.Bound(c => c.filterValue).Title("Value");
	columns.Command(c => c.Destroy()).Width(50);
	})
	.Pageable(pageable => pageable
	.Refresh(true)
	.PageSizes(true))
	.DataSource(dataSource => dataSource
		.Ajax()
		.PageSize(5)
		.Batch(true)
		.ServerOperation(false)
		.Events(events => events.Error("ErrorHandlerForFilterTable"))
		.Model(model =>
		{
			model.Id(p => new { p.filterId });
		})
		.Create("createFilter", "View1")
		.Read(read => read.Action("getFiltersTable", "View1", new { url = @Context.Request.Path }))                                                                                
		.Update("updateFilter", "View1")
		.Destroy(del => del.Action("deleteFilter", "View1"))                                        
	)
)

Alexander
Telerik team
 answered on 30 Apr 2024
1 answer
20 views

I need to send a model to my controller action. I have created a Kendo grid:

Html.Kendo().Grid<XXXX.WebUI.Models.Employees.LocationsListViewModel>()
    .Name("EmployeeLocationsGrid")
    .Columns(columns => {
        columns.Select().Width(45);
        columns.Bound(c => c.UIDEmployee).Visible(false);
        columns.Bound(c => c.UIDEmployee_Location).Title("Id").Width(50);
        if (Model.LocationsEntities != null)
        {
            columns.ForeignKey(f => f.UIDLocation, Model.LocationsEntities?.Items, "UIDEntity", "Name")
                .Title("Location")
                .EditorTemplateName("FieldListLocations")
                .EditorViewData(new { locations = Model.LocationsEntities.Items })
                .Width(200);
        }
        if (Model.LocationsEntities != null)
        {
            columns.ForeignKey(f => f.UIDSublocation, Model.SublocationsEntities?.Items, "UIDEntity", "Name")
                    .Title("Sublocation")
                    .EditorTemplateName("FieldListSublocations")
                    .EditorViewData(new { sublocations = Model.SublocationsEntities.Items })
                    .Width(200);
        }
        columns.Bound(c => c.Main)
            .Title("Main")
            .EditorTemplateName("FieldCheckBox")
            .ClientTemplate("#= Main ? 'Yes' : 'No' #")
            .Width(100);
        columns.Bound(c => c.PercentageOfDedication)
            .Title("% Dedication")
            .EditorTemplateName("FieldNumericTextBox")
            .Format("{0} %")
            .Width(200);
        columns.Bound(c => c.StartDate)
            .Title("Start Date")
            .ClientTemplate("#= kendo.toString(kendo.parseDate(StartDate), 'dd/MM/yyyy') #")
            .EditorTemplateName("FieldDateOnlyPicker")
            .Width(200);
        columns.Bound(c => c.EndDate)
            .Title("End Date")
            .ClientTemplate("#= EndDate != null ? kendo.toString(kendo.parseDate(EndDate), 'dd/MM/yyyy') : '<strong>Currently</strong>' #")
            .EditorTemplateName("FieldDateOnlyPicker")
            .Width(200);
        columns.Bound(c => c.Comments)
            .Title("Comments")
            .EditorTemplateName("FieldTextArea")
            .Width(250);
        columns.Command(command => {
            command.Edit().Text(" ").UpdateText(" ").CancelText(" ").IconClass("bi bi-pencil-square").HtmlAttributes(new { @class = "btn btn-outline-primary", title = "Edit" });
            command.Custom("deleteLocation")
                .Click("function(e) { var dataItemLoc = this.dataItem($(e.target).closest('tr')); window.i3.OnDeleteEmployeeLocation(dataItemLoc); }")
                .Text(" ").IconClass("bi bi-trash3")
                .HtmlAttributes(new { @class = "btn btn-outline-primary", title = "Delete" });
        }).Title("Actions");
    })
    .NoRecords(s => s.Template("<span class='ms-3 mt-3'><i class='bi bi-people-fill me-2'></i><strong>This employee was not assigned to any location.</strong></span>"))
    .AutoBind(true)
    .Editable(editable => editable.Mode(GridEditMode.InLine))
    .Sortable(sorting => sorting.Enabled(true))
    .Selectable(selectable => selectable.Mode(GridSelectionMode.Multiple).DragToSelect(false))
    .Events(events => events
        .Sort("window.i3.OnColumnSorted").Save("window.i3.OnSaveLocation")
    )
    .DataSource(ds => ds
        .Ajax()
        .Model(gridModel =>
        {
            gridModel.Id(entity => entity.UIDEmployee_Location);
            gridModel.Field(p => p.UIDEmployee_Location).Editable(false);
            gridModel.Field(p => p.UIDEmployee).Editable(false).DefaultValue(Model.UIDEmployee);
            gridModel.Field(p => p.UIDLocation).Editable(true);
            gridModel.Field(p => p.UIDSublocation).Editable(true);
            gridModel.Field(p => p.UIDStatus).Editable(false);
            gridModel.Field(p => p.UIDPosition).Editable(false);
        })
        .Read(r => r.Action("GetAllEmployeeLocations", "Employees", new { EmployeeID = Model.UIDEmployee }))
        .Events(events => events
            .RequestEnd("window.i3.OnRequestEndLocation")
        )
        .PageSize(10)
    )
)

This data reaches me at this event where I process it:

public OnSaveLocation(e: kendo.ui.GridSaveEvent): void {
    e.preventDefault();

    const gridLocation = $("#EmployeeLocationsGrid").data("kendoGrid");
    const locationsItems: LocationsListViewModel[] = (gridLocation?.dataSource.data() as unknown) as LocationsListViewModel[];
    let newLocItem: LocationsListViewModel = (e.model as any) as LocationsListViewModel;

    // Fix Date
    let startLocationDateNew = new Date(newLocItem.StartDate);
    let endLocationDateNew = new Date(newLocItem.EndDate);
    let offsetLocationNew = startLocationDateNew.getTimezoneOffset();
    startLocationDateNew = new Date(startLocationDateNew.getTime() - (offsetLocationNew * 60 * 1000));
    endLocationDateNew = new Date(endLocationDateNew.getTime() - (offsetLocationNew * 60 * 1000));

    let newLocationItem: LocationsListViewModel = {
        UIDEmployee_Location: newLocItem.UIDEmployee_Location,
        UIDEmployee: newLocItem.UIDEmployee,
        UIDLocation: newLocItem.UIDLocation,
        UIDSublocation: newLocItem.UIDSublocation,
        UIDPosition: newLocItem.UIDPosition,
        Main: newLocItem.Main,
        PercentageOfDedication: newLocItem.PercentageOfDedication,
        StartDate: startLocationDateNew.toISOString().split('T')[0],
        EndDate: endLocationDateNew.toISOString().split('T')[0],
        UIDStatus: newLocItem.UIDStatus,
        Comments: newLocItem.Comments
    };
}

All the data is well collected except Sublocations is set to null. Where it should be an int ID. I share with you the Template and the model:

@using XXXX.Application.Application.Maintenances.DTOs;

@model int?

@(Html.Kendo().DropDownListFor(m => m)
    .DataTextField("Name")
    .DataValueField("UIDEntity")
    .OptionLabel("Select...")
    .BindTo((IEnumerable<GenericMaintenanceEntityDTO>)ViewData["sublocations"]!)
)
@using XXXX.Application.Application.Maintenances.DTOs;

@model int

@(Html.Kendo().DropDownListFor(m => m)
    .DataTextField("Name")
    .DataValueField("UIDEntity")
    .OptionLabel("Select...")
    .BindTo((IEnumerable<GenericMaintenanceEntityDTO>)ViewData["locations"]!)
)
interface LocationsListViewModel {
    UIDEmployee_Location: number;
    UIDEmployee: number;
    UIDLocation: number;
    UIDSublocation: number;
    UIDPosition: number;
    Main: boolean;
    PercentageOfDedication: string;
    StartDate: string;
    EndDate: string;
    UIDStatus: number;
    Comments: string;
}

I have been looking for the problem for quite some time but I can't find it. Can someone help me?

Thanks

Mihaela
Telerik team
 answered on 26 Feb 2024
1 answer
42 views

I'm using DropDownList in grid as EditorTemplate. If no value is selected I get a message that says "The Id field is required". How to change the message or remove it completely?

Vasko
Telerik team
 answered on 02 Oct 2023
1 answer
41 views

Hi All,

We have a table for managing a business process that needs to display an item from the inventory tables. Therefore we need the column showing what Item a record will use to be a ForeignKey column. We have had various problems getting this to work, and our best solution so far is still not functional. The DropDownList just closes as soon as you click into it. It is bound with server filtering.

The column definition:

columns.ForeignKey(p => p.ItemMasterId, ds => ds.Read(r => r.Action("ItemMasters", "MasterMix")), "ItemId", "ItemName", true)
                                    .Title("Item Name").Width(500).EditorTemplateName("ItemMasterDropDownEditor");

The editor template:

@model object

@(Html.Kendo().DropDownListFor(model => model)
        .DataSource(source =>
        {
            source.Read("ItemMasters", "MasterMix").ServerFiltering();
        })
        .Filter(FilterType.Contains)
        .DataValueField("ItemId")
        .DataTextField("ItemName")
)

The server-side call:

public ActionResult ItemMasters(string text)
        {
            var itemMasters = string.IsNullOrEmpty(text) ? db.ItemMasters.OrderBy(o => o.ItemName).Select(p => new ItemMasterVM(p.Id, p.ItemName)).ToList()
                : db.ItemMasters.OrderBy(o => o.ItemName).Where(e => e.ItemName.ToLower().Contains(text.ToLower())).Select(p => new ItemMasterVM(p.Id, p.ItemName)).ToList();
            return Json(itemMasters);
        }

 

The list is working correctly showing all we need. We just can't get the dropdown to stay open and have the cursor in the filter search text box.

Thanks in advance... Bob Graham

 

Anton Mironov
Telerik team
 answered on 27 Sep 2023
1 answer
45 views

I use a DropDownList as an EditorTemplate in a Grid.

The problem is, that the DDL has to display several thousand entries (products).

I tried to set the PageSize of the DataSource and handle the Filter-Event. This works fine so far.  The DDL opens very fast and I can search (filter) and then select an entry, that is not visible in the list at the beginning.

This works fine for adding a new record.

But when I want to edit an existing record in the grid I get problems. When the editor opens and the value is not in the select list of the DDL, it is not selected (also not displayed) and the value of the DDL is set to null.

This behavior makes sense to me.

When I remove the PageSize from the DataSource everythings works fine. But it takes to long to open the DDL. That's why I need another solution.

I also tried the virtualization. But the problem stays the same.

Does anyone have an idea how I can solve this?

Maybe another control? Finally the user should be able to search and select a product on an easy way.

I am grateful for any idea.

CPS
Top achievements
Rank 1
Iron
Iron
 answered on 06 Sep 2023
2 answers
278 views

How to cascade DropDownList in Grid?

I've tried a lot of stuff using JavaScript, JQuery and Ajax but I can't get this to work. I wasn't able to find an example on how to do this.

This is my code for grid and editor templates...

@(Html.Kendo().Grid<ToDestination>(Model.ToDestinations)
                .Name("grid")
                .Columns(columns =>
                {
                    columns.ForeignKey(c => c.TravelTypeId,
                    (System.Collections.IList)ViewData["TravelTypes"], "TravelTypeId", "TravelTypeName").Title("Travel Type");

                    columns.ForeignKey(c => c.CountryId,
                    (System.Collections.IList)ViewData["Countries"], "CountryId", "CountryName").Title("Country")
                    .EditorTemplateName("CountryEditor"); // Specify a custom editor template for the Country dropdown.

                    columns.ForeignKey(c => c.PlaceId,
                    (System.Collections.IList)ViewData["Places"], "PlaceId", "PlaceName").Title("Place")
                    .EditorTemplateName("PlaceEditor"); // Specify a custom editor template for the Place dropdown.

                    columns.Bound(c => c.PlaceName);
                    columns.Bound(c => c.CenterName);
                    columns.Command(command => { command.Edit(); command.Destroy(); }).Width(250);
                })
                .ToolBar(toolbar => toolbar.Create())
                .Editable(editable => editable.Mode(GridEditMode.InLine))
                .Pageable()
                .Sortable()
                .Scrollable()
                .DataSource(ds => ds.Ajax()
                .Create(c => c.Url("/TravelOrders/Create?handler=Create").Data("forgeryToken"))
                .Read(r => r.Url("/TravelOrders/Create?handler=Read").Data("forgeryToken"))
                .Update(u => u.Url("/TravelOrders/Create?handler=Update").Data("forgeryToken"))
                .Destroy(d => d.Url("/TravelOrders/Create?handler=Destroy").Data("forgeryToken"))
                .Model(m =>
                {
                    m.Id(id => id.ToDestinationId);
                    m.Field(tt => tt.TravelTypeId).DefaultValue(1);
                    m.Field(c => c.CountryId).DefaultValue(1);
                })
                )
                )

@model int? // Assuming CountryId is nullable

@(Html.Kendo().DropDownList()
    .Name("CountriesList")
    .DataTextField("CountryName")
    .DataValueField("CountryId")
    .BindTo((System.Collections.IEnumerable)ViewData["Countries"])
    .OptionLabel("Select a country")
    .Events(e => e.Change("onCountryChange"))
)

@model int? // Assuming PlaceId is nullable

@(Html.Kendo().DropDownList()
    .Name("PlacesList")
    .DataTextField("PlaceName")
    .DataValueField("PlaceId")
    .BindTo((System.Collections.IEnumerable)ViewData["Places"])
    .OptionLabel("Select a place")
)

Alexander
Telerik team
 answered on 29 Aug 2023
1 answer
79 views

I am using a drop down list in column template inside a grid..I could save sucessfully but when i click on edit the dropdown losses its bind.Can any one help  with what i am missing

   <kendo-dropdownlist name="Team"
                                        datatextfield="Team"
                                        datavaluefield="TeamID" data-bind="value:Team">
                        <datasource>
                            <transport>
                                <read url="@Url.Action("Teams_Read", "Grid")" />
                            </transport>
                        </datasource>
                    </kendo-dropdownlist>

 

i chnaged name of the dropdown to the value of what i wante dto bind but it didnt work.

Vasko
Telerik team
 answered on 28 Jul 2023
1 answer
54 views

I have a grid that is inline editable

My problem is when the drop down appears it looks like this

Some of the items wrap around to two rows.  I would like the drop down to expand to fit the width of the text.

I looked in Chrome and I see the item is in an unnamed div that starts with this

<div class="k-animation-container"

I have tried the following in my .css to override the width of the container

.k-animation-container {
	width: auto;
}

and that doesn't seem to have any effect.

Is there a way to change the width of the drop down when it appears without changing the width of the containing column in the grid?

 

Eric
Top achievements
Rank 2
Iron
Iron
 answered on 31 Mar 2023
1 answer
682 views

Hi,

How do we take a drop down with a list of values and put it on a gridview. and save the chosen values as text.

What would be the best way and easiest way ? 

For Example 

I have Table A which is bound to the Grid View. I want to show values from one of the column from Table B as a dropdown list of values in one of the column of the grid view.  There is no foreign key relationship between the tables.

2 EXAMPLE FOR IDEA:

 1) For Example : https://demos.telerik.com/aspnet-core/grid/custom-datasource

How can you add a dropdown list in the product name column, product list is coming from another table where there is no foreign key relationship

2) Another example : https://demos.telerik.com/aspnet-core/grid/foreignkeycolumnbinding  : How can we achieve category binding without a foreign key. 

Aleksandar
Telerik team
 answered on 13 Mar 2023
1 answer
298 views

Hello I have searched multiple forum responses on similar issues for this answer seen the cascading dropdown demos and the MVC5 dropdown demo. I can't seem to make my cascading inline grid dropdown recognize the parent object to enable the second dropdown.

I have been able to access the cascade effect when the initial dropdown is not in the grid. So I can make a dropdown that cascades I just cant seem to get it to work in the grid while editing.

Any suggestions? Thanks!

code below

subedit.cshtml

@model CircuitStatus

@(Html.Kendo().DropDownList() .Name("subdrop") .OptionLabel("Select option") .DataTextField("station_name") .DataValueField("station_id") .DataSource(source => { source.Read(read => { read.Action("station_Read", "CircuitStatus"); }).ServerFiltering(true); }) )

 

cascadedropdowntemplate.chtml

@(Html.Kendo().DropDownList()
          .Name("circuit")
          .HtmlAttributes(new { style = "width:100%" })
          .OptionLabel("Select product...")
          .DataTextField("circuit_name")
          .DataValueField("circuit_id")
          .DataSource(source =>
                  {
              source.Read(read =>
              {
                  read.Action("cirucitBystation_Read", "CircuitStatus")
                      .Data("getSubstationName");
              })
              .ServerFiltering(true);
          })
          .Enable(false)
          .AutoBind(false)
          .CascadeFrom("subdrop")

          )

<script type="text/javascript">
    function getSubstationName() {
        console.log($("#subdrop").val());
        return {
            circuitbySubstationName: $("#subdrop").val()
        };
    }
</script>

finally the index.cshtml

<div class="row"><div class="col-12"> @(Html.Kendo().Grid<QCReview.Models.CircuitStatus>() .Name("grid") .Columns(columns => { columns.Bound(p => p.STATION_NAME).EditorTemplateName("subedit").Filterable(filterable => filterable.Multi(true).CheckAll(true)); columns.Bound(p => p.CIRCUIT_ID).Title("Circuit ID").EditorTemplateName("cascadedropdowntemplate"); columns.Bound(p => p.QA_EXT).ClientTemplate("<input type='checkbox' disabled #=QA_EXT ? checked='checked' :'' # />").Title("QA Ready"); columns.Bound(p => p.OMS_READY).ClientTemplate("<input type='checkbox' disabled #=OMS_READY ? checked='checked' :'' # />").Title("OMS Ready"); columns.Bound(p => p.INSERT_DATETIME).Format("{0:MM/dd/yyyy}").Title("Insert Date"); columns.Bound(p => p.QA_DATETIME).Format("{0:MM/dd/yyyy}").Title("QA Date"); columns.Bound(p => p.LAST_UPDATE_DATETIME).Format("{0:MM/dd/yyyy hh:mm tt}").Title("Last Update Date"); columns.Command(command => { command.Edit(); command.Destroy(); }).Width(172); }) .Events(events => events.Edit("edit") ) .ToolBar(toolbar => toolbar.Create()) .Editable(editable => editable.Mode(GridEditMode.InLine)) .Pageable() .Sortable() .Scrollable() .Filterable(filter => filter.Extra(false) .Operators(operators => operators .ForString(str => str.Clear() .StartsWith("Starts with") .IsEqualTo("Is equal to") .IsNotEqualTo("Is not equal to") ))) .Groupable() .HtmlAttributes(new { style = "height:550px;" }) .DataSource(dataSource => dataSource .Ajax() .PageSize(50) .Events(events => { events.Error("error_handler"); events.Change("onChange"); }) .Model(model => { model.Id(p => p.CIRCUIT_ID); model.Field(p => p.STATION_NAME).Editable(true); model.Field(p => p.CIRCUIT_ID).Editable(true); model.Field(p => p.INSERT_DATETIME).Editable(false); model.Field(p => p.SUBSTATION_NAME).Editable(true); model.Field(p => p.LAST_UPDATE_DATETIME).Editable(false); }) .Create(create => create.Action("CircuitStatus_Create", "CircuitStatus")) .Read(read => read.Action("CircuitStatus_Read", "CircuitStatus")) .Update(update => update.Action("CircuitStatus_Update", "CircuitStatus")) .Destroy(update => update.Action("CircuitStatus_Destroy", "CircuitStatus")) ) )

<script type="text/javascript">
    function getSubstationName() {
        console.log($("#subdrop").val());
        return {
            circuitbystationName: $("#subdrop").val()
        };
    }
</script>

 


 

 

 

Jack
Top achievements
Rank 1
 updated question on 14 Feb 2023
Narrow your results
Selected tags
Tags
+? more
Top users last month
Mark
Top achievements
Rank 1
Yurii
Top achievements
Rank 1
Leland
Top achievements
Rank 2
Iron
Iron
Iron
Hon
Top achievements
Rank 1
Iron
Deltaohm
Top achievements
Rank 3
Bronze
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Mark
Top achievements
Rank 1
Yurii
Top achievements
Rank 1
Leland
Top achievements
Rank 2
Iron
Iron
Iron
Hon
Top achievements
Rank 1
Iron
Deltaohm
Top achievements
Rank 3
Bronze
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?