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

Working with a Dropdown and a Grid using Northwind database?

5 Answers 366 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Donald
Top achievements
Rank 1
Donald asked on 24 Oct 2012, 02:17 PM
Hi guys,

I have a simple example I have created to try get the kendo stuff working stably on my machine before I think about purchasing it. However, I am struggling to get simple behaviour working which am sure should not be a problem. I am using MVC and what I am trying to do is to refresh my grid below my drop down when I select a Supplier in the dropdown. My grid is populated with products and would want it to reduce the collection and show only the products for a supplier. Code Below:

Partial View 1:
@using Kendo.Mvc.UI
@model IEnumerable<NorthwindKendo.ViewModels.SupplierViewModel>
<div id="supplier" style="width300px;">
    @(Html.Kendo().DropDownList()
           .Name("suppliers")
           .DataTextField("CompanyName")
           .DataValueField("SupplierID")
           .Events(e => e.Change("change"))
           .BindTo(Model)
           .SelectedIndex(-1)
          )
</div>
<script>
    function change() {
        var filterGrid = $("#grid").data("kendoGrid");
         var valu = $("#suppliers").val();
         $.ajax({
             url: "/Product/Grid",
             dataType: "json",
             data: { supplierId: valu },
             success: function (result) {
                 //filterGrid.dataSource.read();
                 //filterGrid.dataSource.fetch();
                 //alert("OK");
                 $("#grid").data("kendoGrid").dataSource.read(); 
                 //filterGrid.dataSource.read();
                 filterGrid.refresh();
             }
         });
     };
</script> Partial View 2:
@model IEnumerable<NorthwindKendo.ViewModels.ProductViewModel>
    
<div id="clientsDb">
    @(Html.Kendo().Grid(Model)
           .Name("grid")
           .Columns(columns =>
                {
                    columns.Bound(p => p.ProductID).Visible(false).Groupable(false);
                    columns.Bound(p => p.ProductName)
                        .ClientFooterTemplate("Total Products: #=count#");
                    columns.Bound(p => p.QuantityPerUnit);
                    columns.Bound(p => p.SupplierID);
                    columns.Bound(p => p.ReorderLevel);
                    columns.Bound(p => p.UnitPrice).Width(90);
                    columns.Bound(p => p.UnitsInStock).Width(120);
                    columns.Command(command => { command.Edit(); command.Destroy(); }).Width(200);
                })
            .ToolBar(toolbar => toolbar.Create())
            .Editable(editable => editable.Mode(GridEditMode.InLine))
            .Pageable()
            .Sortable()
            .Navigatable()
            .ColumnMenu()
            .Resizable(resize => resize.Columns(true))
            .Selectable(selectable => selectable.Mode(GridSelectionMode.Single))
            .DataSource(dataSource => dataSource
                .Ajax()
                .ServerOperation(false)
                .Model(model =>
                {
                    model.Id(info => info.ProductID);
                    model.Field(p => p.ProductID).Editable(false);
                    model.Field(p => p.ProductName).Editable(true);
                    model.Field(p => p.QuantityPerUnit).Editable(true);
                    model.Field(p => p.UnitPrice).Editable(true);
                    model.Field(p => p.SupplierID).Editable(false);
                })
                .Aggregates(aggregates =>
                {
                    aggregates.Add(p => p.ProductName).Count();
                })
                .Events(events => events.Error("error_handler"))
                .PageSize(10)
                .Create(update => update.Action("Create""Product"))
                .Read(read => read.Action("Grid""Product"))
                .Update(update => update.Action("Save""Product"))
                .Destroy(update => update.Action("Delete""Product"))
                )
    )
</div>
<script type="text/javascript">
    function error_handler(e) {
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            alert(message);
        }
    }
</script>
Product Controller :

public class ProductController : Controller
    {
        public ProductController()
        {
            Mapper.CreateMap<ProductProductViewModel>();
            Mapper.CreateMap<CategoryCategoryViewModel>();
            Mapper.CreateMap<SupplierSupplierViewModel>();
        }
        public List<SupplierViewModel> Suppliers
        {
            get
            {
                var viewModels = Repository.GetViewModelCollection<SupplierSupplierViewModelNorthWindDataContext>(); ;
                return viewModels;
            }
        }
        //
        // GET: /Product/
        public ActionResult Index()
        {
            ViewData["Suppliers"] = Suppliers;
            return View();
        }

        public JsonResult Grid()
        {
            ViewData["Suppliers"] = Suppliers;
            var supplierId = Request["supplierId"];


            var viewModels = ProductControllerHelper.GetViewModels<ProductProductViewModelNorthWindDataContext>(supplierId, info => info.SupplierID == Convert.ToInt32(supplierId));
            var kendoResult = new Kendo.Mvc.UI.DataSourceResult
            {
                Data = viewModels,
                Total = viewModels.Count()
            };
            return Json(kendoResult, JsonRequestBehavior.AllowGet);
        }
    }


Please ignore the helper classes as these return the correct data, How ever, I am able to get the id coming through if I put a breakpoint but after 'Json(kendoResult, JsonRequestBehavior.AllowGet);' nothing happens and my grid remains the same, Please assist?

5 Answers, 1 is accepted

Sort by
0
Accepted
Vladimir Iliev
Telerik team
answered on 29 Oct 2012, 04:29 PM
Hi Donald,

 

Basically in the Change event of the DropDownList you should call the Read method of the DataSource with Data parameter function which returns the current value of the DropDownList. Please check the example below:

Partial View1:
@using Kendo.Mvc.UI
@model IEnumerable<NorthwindKendo.ViewModels.SupplierViewModel>
<div id="supplier" style="width: 300px;">
    @(Html.Kendo().DropDownList()
           .Name("suppliers")
           .DataTextField("CompanyName")
           .DataValueField("SupplierID")
           .Events(e => e.Change("change"))
           .BindTo(Model)
           .SelectedIndex(-1)
          )
</div>
<script>
    function change() {
        $("#grid").data("kendoGrid").dataSource.read();
    };
</script>

PartialView2:
@model IEnumerable<NorthwindKendo.ViewModels.ProductViewModel>
     
<div id="clientsDb">
    @(Html.Kendo().Grid(Model)
           .Name("grid")
           .Columns(columns =>
                {
                    columns.Bound(p => p.ProductID).Visible(false).Groupable(false);
                    columns.Bound(p => p.ProductName)
                        .ClientFooterTemplate("Total Products: #=count#");
                    columns.Bound(p => p.QuantityPerUnit);
                    columns.Bound(p => p.SupplierID);
                    columns.Bound(p => p.ReorderLevel);
                    columns.Bound(p => p.UnitPrice).Width(90);
                    columns.Bound(p => p.UnitsInStock).Width(120);
                    columns.Command(command => { command.Edit(); command.Destroy(); }).Width(200);
                })
            .ToolBar(toolbar => toolbar.Create())
            .Editable(editable => editable.Mode(GridEditMode.InLine))
            .Pageable()
            .Sortable()
            .Navigatable()
            .ColumnMenu()
            .Resizable(resize => resize.Columns(true))
            .Selectable(selectable => selectable.Mode(GridSelectionMode.Single))
            .DataSource(dataSource => dataSource
                .Ajax()
                .ServerOperation(false)
                .Model(model =>
                {
                    model.Id(info => info.ProductID);
                    model.Field(p => p.ProductID).Editable(false);
                    model.Field(p => p.ProductName).Editable(true);
                    model.Field(p => p.QuantityPerUnit).Editable(true);
                    model.Field(p => p.UnitPrice).Editable(true);
                    model.Field(p => p.SupplierID).Editable(false);
                })
                .Aggregates(aggregates =>
                {
                    aggregates.Add(p => p.ProductName).Count();
                })
                .Events(events => events.Error("error_handler"))
                .PageSize(10)
                .Create(update => update.Action("Create", "Product"))
                .Read(read => read.Action("Grid", "Product").Data("getSelectedSupplier"))
                .Update(update => update.Action("Save", "Product"))
                .Destroy(update => update.Action("Delete", "Product"))
                )
    )
</div>
<script type="text/javascript">
    function getSelectedSupplier() {
        var currentValue = $("#suppliers").data("kendoDropDownList").value();
        return { supplierId: currentValue };
    }
 
    function error_handler(e) {
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            alert(message);
        }
    }
</script>

Controller Grid Action:
public JsonResult Grid(int? supplierId)
        {
            if(supplierId != null)
            {
               //send filtered data
            }
            else
            {
                //send full data if needed
            }
        }
Kind Regards,
Vladimir Iliev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Tam
Top achievements
Rank 1
answered on 22 Nov 2013, 12:07 AM
I am not able to get the code below to work. The javascript function "getNumberOfDays" was never fired so the "RefreshUpcomingBillsAjax" action always has null for for "numberOfDaysToRetrieve". Please help!

View:
-----------------------------------------------------------------
@section Right
{
<h1>@Html.GlobalResource("String", "Views_Accounts_Home_Index_UpcomingBills_Title")</h1>
@(Html.Kendo().DropDownListFor(m => m.NumberOfDaysToRetrieve)
.Name("number-of-days-dropdown-list")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem> 

new SelectListItem { Text = @Html.GlobalResource("String", "Views_Accounts_Home_Index_Dropdown_Frequency_Seven"), Value = "7" },
new SelectListItem { Text = @Html.GlobalResource("String", "Views_Accounts_Home_Index_Dropdown_Frequency_Fourteen"), Value = "14" },
new SelectListItem { Text = @Html.GlobalResource("String", "Views_Accounts_Home_Index_Dropdown_Frequency_Thirty"), Value = "30" },
})
.Events(e => e.Change("change"))
.HtmlAttributes(new { @autofocus = "autofocus" }))

@(Html.Kendo().Grid(this.Model.Bills)
.Name("upcoming-bills-grid")
.DataSource(
ds =>
ds.Ajax()
.Sort(sort => sort.Add(m => m.DueDate).Ascending())
.Read(read => read.Action("RefreshUpcomingBillsAjax", "Home").Data("getNumberOfDays")))
.TableHtmlAttributes(new { @class = "table table-striped table-upcoming-bills" })
.Columns(
columns =>
{
columns.Bound(t => t.DueDate).Format("{0:MMM d}")
.Title(Html.GlobalResource("Strings", "Views_Accounts_Home_Index_ColumnHeader_Date"))
.HtmlAttributes(new { @class = "column-date" })
.HeaderHtmlAttributes(new { @class = "column-date" });
columns.Template(@<text></text>)
.ClientTemplate("<span class='aspui-icon-view-bill'></span>")
.HtmlAttributes(new { @class = "column-icon" })
.HeaderHtmlAttributes(new { @class = "column-icon" });
columns.Bound(t => t.Name)
.Title(Html.GlobalResource("Strings", "Views_Accounts_Home_Index_ColumnHeader_Description"))
.HtmlAttributes(new { @class = "column-description" })
.HeaderHtmlAttributes(new { @class = "column-description" });
columns.Bound(t => t.AmountDue)
.ClientTemplate(Html.ActionLink("#= DisplayAmountDue #", "Index", "BillPayment", new { paymentId = "id", numberOfDaysToRetrieve = "frequency" }, new { @class = "dialog-lazy", title = "link-title" }).ToHtmlString().Replace("id", "#= Id #").Replace("frequency", @Model.NumberOfDaysToRetrieve.ToString(CultureInfo.InvariantCulture)).Replace("link-title", Html.GlobalResource("Strings", "Views_Accounts_Home_Index_BillPayment")))
.HtmlAttributes(new { @class = "column-amount" })
.HeaderHtmlAttributes(new { @class = "column-amount" });
})
.Sortable(sort => sort.SortMode(GridSortMode.SingleColumn).AllowUnsort(false))
.ConfigureGrid(String.Format(Html.GlobalResource("Strings", "Views_Accounts_Home_Index_NoUpcomingBills"), Model.NumberOfDaysToRetrieve))
.Deferred()
)

<div class="adspace adspace-trends">
@{ Html.RenderAction("Index", "Home", new { area = "Ads", adSpaceId = "TrendsAdSpace" }); }
</div>
}

@section BodyScripts
{
<script>
function getNumberOfDays() {
var currentValue = $("#number-of-days-dropdown-list").data("kendoDropDownList").value();
function getNumberOfDays() {
var currentValue = $("#number-of-days-dropdown-list").data("kendoDropDownList").value();
return { numberOfDaysToRetrieve: currentValue };
}

function change() {
$('#upcoming-bills-grid').data('kendoGrid').dataSource.read();
};
</script>
}

Controller's Action:
-----------------------------------------------------------------
public virtual async Task<ActionResult> RefreshUpcomingBillsAjax([DataSourceRequest] DataSourceRequest request, int? numberOfDaysToRetrieve)
{
var response = await this.GetUpcomingBills(numberOfDaysToRetrieve ?? 7);
return this.Json(response.ToDataSourceResult(request));
}
0
Vladimir Iliev
Telerik team
answered on 26 Nov 2013, 04:09 PM
Hi Tay,

Your question is not related to the original topic of this support conversation, so please open a new support ticket for it and include runable example where the issue is reproduced. That way we will be able to help you straight away.

Regards,
Vladimir Iliev
Telerik
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Swarna Priya
Top achievements
Rank 1
answered on 08 Dec 2015, 10:33 AM

Hi Vladimir,
I am in same scenario like when the dropdown list changes then grid should be reloaded. it is working fine for me if i use below code in the drop down change event, but i have made the default refresh button of grid as true. hence when i click on refresh it is not loading the value for new data of dropdown.

please help ASAP

change: function (e) {
                    $("#" + gridname).data("kendoGrid").dataSource.read(getAuditparamter("WorkDetails"));
                    }

 $('#' + gridname).kendoGrid({
                dataSource: {
                    transport: {
                        read: {
                            url: window.environment.siteRootUrl + "url",
                            data: getAuditparamter(gridName),
                            dataType: "json",
                            cache: false
                        }
                    },
                    pageSize: 25,
                    serverPaging: true,
                    sort: {
                        field: "EventDate",
                        dir: "desc"
                    }
                }

 

  function getAuditparamter(gridname) {
            
            if (gridname == "WorkDetails") {
                var ddlTaskName = $("#ddl" + gridName).data("kendoDropDownList").text();
                return { id : workId,taskName: ddlTaskName.trim()};
                
            }
        }

0
Vladimir Iliev
Telerik team
answered on 11 Dec 2015, 08:48 AM
Hi Swarna,

I would suggest to try modifying the "change" method of the DDL as follows:

change: function (e) {
 //make sure the grid name is the correct one
 $("#" + gridname).data("kendoGrid").dataSource.read();
}

Also when the "serverPaging" option is enabled and you click on the refresh button the grid should make "read" request, which will call the "getAuditparamter" method and pass the result to the server. If this is not the case, please open a new support ticket / forum post and provide runable example where the issue is reproduced. This would help us pinpoint the exact reason for it. 

Regards,
Vladimir Iliev
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
Tags
Grid
Asked by
Donald
Top achievements
Rank 1
Answers by
Vladimir Iliev
Telerik team
Tam
Top achievements
Rank 1
Swarna Priya
Top achievements
Rank 1
Share this question
or