Telerik Forums
UI for ASP.NET MVC Forum
2 answers
801 views

I'm working on a Kendo UI Grid using ASP.NET MVC. We're having an issue with the grid sticking on a specific page. If the user makes their selections and the grid brings back ten pages, it displays fine. However, if the user makes navigates to page 10 and then makes another selection that only brings back 5 pages, the grid is blank, but the correct page numbers display. If the user clicks on one of the page numbers, the data displays correctly.
Here's my grid:

@(Html.Kendo().Grid<SMT.Models.SpecimenDetail>()
        .Name("SpecimenDetailGrid")
        .Columns(columns =>
        {
            columns.Bound(e => e.uniqueID).Hidden();
            columns.Bound(e => e.SampleID).Width(180).Title("Specimen ID").ClientTemplate("#= fileLinks(data) #");
            columns.Bound(e => e.contactId).Hidden();
            columns.Bound(e => e.contact_business_email).Width(120).Title("Owner Email");
            columns.Bound(e => e.contact_business_phone).Width(120).Title("Owner Phone");
        })
        .ToolBar(tools =>
                {
                    tools.Excel();
                    tools.Custom().Text("Back to Specimen Summary").HtmlAttributes(new { id = "goBack", style = "margin-left: 880px;" });
                })
        .Excel(excel => excel
            .AllPages(true)
            .FileName("SpecimenDetailGridData.xlsx")
            .Filterable(true)
            .ProxyURL(Url.Action("Excel_Export_Save", "Home"))
            )
        .Resizable(x => x.Columns(true))
        .Reorderable(x => x.Columns(true))
        .Scrollable()
        .Sortable()
        .HtmlAttributes(new { style = "height:500px;" })
        .Pageable()
        .Filterable()
        .AutoBind(false)
        .Editable(e => e.Mode(GridEditMode.InLine))
        .DataSource(datasource => datasource
            .Ajax()
                    .Model(model => {
                        model.Id(p => p.uniqueID);
                        model.Field(p => p.SampleID).Editable(false);
                        model.Field(p => p.company_business_name).Editable(false);
 
                        // disable company name on edit
                        // model.Field(p => p.company_business_name).Editable(false);
                    })
            .Read(read => read.Action("GetSpecimenDetail", "Home").Data("FillSearchParms"))
            .Update(update => update.Action("UpdateSpecimen", "Home").Data("FillUpdateParms"))
            .Destroy(destroy => destroy.Action("DeleteSpecimen", "Home"))
            .PageSize(10)
            .Events(e => { e.RequestEnd("onRequestEnd");})
            )
    )

 

Here's the call that fires off the search:

    $(document).ready(function () {
 
    $("#divSearchSpecimenDetail").attr("style", "display: none;");
 
    $("#SearchBtn").click(function (e) {
        e.preventDefault();
 
       //debugger;
        var selectedSpecimen = $('#SpecimenCategory').data("kendoDropDownList").text();
        if (selectedSpecimen == "-- Select --") {
            alert("Please select Specimen Category");
            return;
        }
 
        var selectedUnits = $('#Units').data("kendoDropDownList").text();
        if (selectedUnits == "") {
            alert("Please select Units");
            return;
        }
 
        var units = defaultDDObj("Units");
        var specimenCat = defaultDD("SpecimenCategory");
 
        $("#divSearchSpecimenDetail").attr("style", "display: block;");
       //debugger;
        var grid = $("#SpecimenDetailGrid").data("kendoGrid");
        grid.dataSource.read();
        grid.refresh();
        grid.pager.refresh();
 
        e.preventDefault();
 
        hideColumns(specimenCat);
 
        $("#searchbar").data("kendoPanelBar").collapse($("li.k-state-active"));
    })
});

Really stuck here, thanks in advance
Nathan
Top achievements
Rank 1
 answered on 05 Dec 2016
2 answers
1.0K+ views

I have a Kendo Grid that uses Ajax. I want one of my columns to be unbound and to also use a client template. One hack is to do this:

 

columns.Template(@<text>Unused</text>).Title("SomeTitle").ClientTemplate("#=myTemplateFunction(data)#");

 

However, it is definitely a hack. Is there a better way to accomplish using a client template and have an unbound column?

Bo Chulindra
Top achievements
Rank 1
 answered on 02 Dec 2016
3 answers
1.2K+ views

My aim is to delete the row when the Command Destroy column is clicked if the built in Confirmation popup if confirmed.

Want: Click Destroy Column > Confirm OK > ActionReult Triggered

Cannot use auto-sync since aiming at keeping other updates and inserts still require the save to be clicked to commit.

 

Currently the code will remove the row from the display when it is clicked as is built in.

And only after the save button for the grid is clicked does it trigger the ActionResult "OfficerDestroy" for doing so.

 

Seems there should be some event in this process that could trigger the ActionResult.

What are the options here for triggering that ActionResult while having a confirmation?

 

@(Html.Kendo().Grid<NexusPWI.ViewModels.Wizard.gridData>()
    .Name("OfficerGrid")
    .Columns(c => {
        c.Bound(vm => vm.GridId); //Can display for testing purposes
        c.Bound(vm => vm.FirstName).Width(50);
        c.Bound(vm => vm.LastName).Width(50);
        c.Bound(vm => vm.Title).Width(50);
        c.Command(command => { command.Destroy(); }).Width(30);
    })
    .Editable(editable => editable.Mode(GridEditMode.InCell))
    .Navigatable()
    .Pageable()
    .DataSource(dataSource => dataSource
        .Ajax()
        .Batch(true)
        .ServerOperation(false)
        .Events(events => events.Error("officerGrid_error") // Handle the "error" event
            .RequestEnd("officerGrid_RequestEnd") // Handle the "RequestEnd" event
            .Change("officerGrid_Delete")
            )
        .Model(model => model.Id(vm => vm.GridId))
        .PageSize(1000)
        .Create("OfficerCreate", "Wizard")
        .Read("OfficerRead", "Wizard")
        .Update("OfficerUpdate", "Wizard")
        .Destroy("OfficerDestroy", "Wizard")//.AutoSync(true)
))

<script>

function officerGrid_RequestEnd(e) {
        if (e.type == "update" || e.type == "create") {
            this.read();
        }
    }
</script>


public ActionResult OfficerDestroy([DataSourceRequest] DataSourceRequest request, IEnumerable<gridData> models)
{//This code works fine
}

Pavlina
Telerik team
 answered on 02 Dec 2016
4 answers
271 views

hi, im using asp.net 5 with MVC 6 and i have 2 problem using GridEditMode.PopUp

----------------------------------------------------- view ----------------------------------------------------------------------------

 @(Html.Kendo().Grid<Organization>()  .Name("grid")

.Columns(columns =>             {                

 columns.Bound(p => p.Name).Title("Name");

columns.Bound(p => p.Email).Title("Email");

 columns.Bound(p => p.Disabled).Title("Disabled").Width(120);                         columns.Command(command => { command.Edit(); command.Destroy(); }).Width(150);             })

.HtmlAttributes(new { style = "height: 550px;" })             

.ToolBar(toolbar => toolbar.Create().Text("Add"))             

.Editable(editable =>{ editable.Mode(GridEditMode.PopUp); editable.TemplateName("Edit"); })             

.Pageable( pageable => pageable .Input(false) .Numeric(false) ) .Filterable().Sortable().Scrollable()          .Events(events => events.Edit("insertPopupCaption"))             

.DataSource(dataSource => dataSource.Ajax().PageSize(11).Events(events => events.Error("grid_error"))

.Model(model =>  {                        

 model.Id(p => p.Id);                         

model.Field(p => p.Name).Editable(false);

model.Field(p => p.Email).Editable(true);                         

model.Field(p => p.Disabled); })

.Create(update => update.Action("Create", "Organization"))

.Read(read => read.Action("GetAll", "Organization"))                

 .Update(update => update.Action("Update", "Organization"))                 

.Destroy(update => update.Action("Delete", "Organization"))     )             )

-----------------------------------------------------------------------------------------------------------------------------------

Problems:

 1- As you can see im using editable.TemplateName("Edit") but this template is never found in the path "/view/Organization/EditorTemplates/Edit.cshtml" the only way to make it works is using the template in the path  "/view/Shared/EditorTemplates/Edit.cshtml" (i have seen projects with mvc5 and this problem never happens)

 

2- if i try to remove the tag editable.TemplateName("Edit");  tring to use the template by default, this template seems to dont have in account the model because  the field NAME "model.Field(p => p.Name).Editable(false);" is set to as not edittable BUT IN THE POPUP IT CAN BE EDITTABLE...

 

 Thanks for your help...

 

 

Lo
Top achievements
Rank 1
 answered on 02 Dec 2016
2 answers
84 views

I'm following this example to export my grid to PDF: http://demos.telerik.com/aspnet-mvc/grid/pdf-export

In the pdf configuration, I'd need to use both pdf.TemplateId and pdf.RepeatHeaders, but when try to use them in my grid I get the following error: "Cannot resolve symbol TemplateId", and same with RepeatHeaders. I've attached and image showing this behaviour.
I'd like to know how to use those configurations properly.

Thanks in advance

Matias
Top achievements
Rank 1
 answered on 01 Dec 2016
2 answers
349 views

I've got a grid using the InCell edit mode with a custom editor template, and I'm trying to select all the text when the user clicks the cell to edit.  I've seen (and tried) several suggestions in other forums, but they simply don't work for me.  Currently, I'm down to this, which doesn't work but seems like it should:

Editor template:

@model decimal?
 
@(Html.Kendo().NumericTextBoxFor(m => m)
      .Decimals(2)
      .RestrictDecimals(true)
      .Spinners(false)
      .HtmlAttributes(new { style = "width:100%" })
)

 

In the client-side edit handler:

e.container.find('input').each(function () {
  var editor = this;
  setTimeout(function () { editor.select(); });
});

 

The reason I'm using .each is that there seems to be two input elements in the edit container.  I've tried .select on each of them individually, to no avail.

Any thoughts on this?

Chris T.
Top achievements
Rank 1
 answered on 01 Dec 2016
2 answers
209 views

Hello,

I'm trying to install Asp .NET MVC extensions in Visual Studio Professional 2013 via NuGet. NuGet keeps asking for the password even though I am sure it is correct. I have tried resetting the password twice without effect.

In package.json there is:

    <package id="Telerik.UI.for.AspNet.Mvc5" version="2016.3.1118" targetFramework="net452" />

 

Paul
Top achievements
Rank 1
 answered on 01 Dec 2016
6 answers
156 views

I am instantiating a custom command inside a grid.
If a certain condition is met, the command button (.k-grid-AddNewThing) is appended with the ("k-state-disabled") style class to disable the button.
This works great on load when wired up to the .DataBound event.

However, when the Edit button is clicked and subsequently the Cancel button is clicked, the ("k-state-disabled") style class is removed and reverted to the default.

I have tried to wire up the .Cancel event to re-apply the ("k-state-disabled") style class, but it seems that the .Cancel event is ansyncly firing the default action along with my custom function. 

There are two paths that i figure.

1. Client Template w/Conditional: this would be favorable, since i can remove the javascript function completely.
2. Somehow implement a callback/promise in the default .Cancel event.

I don't know if any of these are possible though.

Any ideas?

 

Grid Helper Event Method

.Events(e => { e.DataBound("disableCustomCommand"); e.Cancel("disableCustomCommand"); })

 

JS function:

    function disableCustomCommand(e) {
        var grid = this;
        grid.tbody.find("tr[role='row']").each(function () {
            var model = grid.dataItem(this);
            if (model.isVerified == true) {
                $(this).find(".k-grid-AddNewThing").addClass("k-state-disabled").text("NewThing Exists");
            }
        });
    }
//This works perfectly on the .DataBound event, but does not process properly when called by the .Cancel event and reverts to default style class, giving the impression that the .find() method did not find the element or the .addClass() method did not apply the style.

 

 

Chris
Top achievements
Rank 1
 answered on 30 Nov 2016
7 answers
1.5K+ views

Hi, 

I am attempting to set the initial value of an input control inside the Popup editor by using a hierarchical grid's Edit event. The popup displays correctly, but the MVVM binding is not updating the model. This is the case for any of the input controls i try to set the value of. However, if i manually (non-programmatically) change the input value, the model is successfully updated. I have also tried to use the .data("").trigger("change") method to fire off the change event of the input control to no avail. I have tried setting the value on several other controls (not just a dropdownlist) and the result is the same-the display text is shown correctly but the value is not updated in the model. Any ideas on how to update the model?

Below is the Grid Helper, Javascript function, and Editor Template. Attached is a screenshot of the form data; notice how CourseID is set to 0 (CourseID is non-nullable).

 

MVC Grid Helper: 

<script id="childTemplate" type="text/kendo-tmpl">
        @(Html.Kendo().TabStrip()
                    .Name("tabStrip_#=CourseID#")
                    .SelectedIndex(0)
                    .Animation(a => a.Open(o => o.Fade(FadeDirection.In)))
                    .Items(i =>
                    {
                        i.Add().Text("Classes").Content(@<text>
                            @(Html.Kendo().Grid<LMS_Web_MVC.Models.ClassFull>()
                            .Name("grid_#=CourseID#")
                            .ToolBar(t => t.Create().Text("Add Class"))
                            .Columns(columns =>
                            {
                                columns.Bound(o => o.ClassID);
                                columns.Bound(o => o.BeginDate).Format("{0:yyyy-MM-dd HH:mm}");
                                columns.Bound(o => o.EndDate).Format("{0:yyyy-MM-dd HH:mm}");
                                columns.Bound(o => o.Enrollees);
                                columns.Bound(o => o.Active);
                                columns.Command(c => { c.Edit(); }).Title("Actions");

                            })
                            .Editable(e => e.Mode(GridEditMode.PopUp).Window(w => w.Width(600)).TemplateName("ClassEditor"))
                            .DataSource(dataSource => dataSource
                                .Ajax()
                                .PageSize(10)
                                .Read(read => read.Action("Get_ClassesByCourse", "Class", new { courseID = "#=CourseID#" }))
                                .Update(u => u.Action("SaveClass", "Class"))
                                .Create(c => c.Action("SaveClass", "Class"))
                                .Model(m => { m.Id(c => c.ClassID); m.Field(c => c.Active).DefaultValue(true);
                                })
                            )
                            .Events(ev => ev.Edit("onEdit"))
                            .Pageable()
                            .Sortable()
                            .ToClientTemplate())
                        </text>);
                    }
        ).ToClientTemplate())
</script>

 

Javascript Function

<script>

    function onEdit(e) {
        if (e.model.ClassID == null) {
            var courseGrid = $("#grid").data("kendoGrid");
            var parentRow = courseGrid.dataItem(this.wrapper.closest("tr").prev());
            var id = parentRow.CourseID;
            $("#CourseID").data("kendoDropDownList").value(id);
            $("#CourseID").data("kendoDropDownList").trigger("change");
        }

</script>

 

Editor Template

@model LMS_Web_MVC.Models.ClassFull

<div data-container-for="CourseID" class="k-edit-field">
    @Html.Kendo().DropDownListFor(model => model.CourseID).OptionLabel("Choose Course").Filter(FilterType.Contains).HtmlAttributes(new { style = "width:400px" }).DataTextField("CourseTitle").DataValueField("CourseID").ValuePrimitive(true).DataSource(ds => {
    ds.Custom()
    .ServerFiltering(true)
    .ServerPaging(true)
    .PageSize(100)
    .Type("aspnetmvc-ajax")
    .Transport(t =>
    {
        t.Read("Get_SimpleCourseList", "Course", new { filterActive = false });
    })
    .Schema(s =>
    {
        s.Data("Data").Total("Total");
    });
}).Virtual(v => v.ItemHeight(26).ValueMapper("valueMapper"))
</div> 

 

Chris
Top achievements
Rank 1
 answered on 30 Nov 2016
1 answer
91 views

Hi all, I've problem to load drop down list inside kendo grid foreign key column:

My configuration is the following:
I have a view

@model Pomini.DeviceMonitor.Configurator.Models.Device.DeviceSearchModel
 
@{
    ViewBag.Title = "Device";
    Layout = "~/Views/Shared/_DefaultLayoutForKendoGrid.cshtml";
}
 
@section PageScript {
    <script src="~/Scripts/device.js"></script>
}
 
<div class="row">
 
    <div class="col-md-12">
        <h1>Device List of @Model.RollshopName</h1>
 
        @(Html.Kendo().Grid<Pomini.DeviceMonitor.Business.Device>(Model.DeviceList)
            .Name("DeviceGrid")
            .Columns(columns =>
            {
            columns.Bound(p => p.DeviceID);
            columns.Bound(p => p.SerialNumber);
            columns.ForeignKey(p => p.DeviceType, @Model.DeviceTypeEnumList, "Value", "Name");
            columns.Template(@<text></text>).ClientTemplate(@Html.ActionLink("View Configuration", "Index", "Item", new { deviceId = "#=DeviceID#" }, null).ToHtmlString());
            })
            .Pageable()
            .Sortable(sortable =>
            {
                sortable.Enabled(true);
                sortable.SortMode(GridSortMode.SingleColumn);
            })
            .Filterable()
            .ToolBar(toolbar =>
            {
                toolbar.Create();
                toolbar.Save();
            })
            .Editable(editable =>
            {
                editable.Mode(GridEditMode.InCell);
                editable.Enabled(true);
                editable.DisplayDeleteConfirmation(true);
            })
            .Navigatable()
            .DataSource(dataSource =>
                dataSource.Ajax()
                .Batch(true)
                .Model(model =>
                {
                    model.Id(p => p.DeviceID);
                    model.Field(p => p.DeviceID).Editable(false);
                })
                .Read(read => read.Action("Device_Read", "Device"))
                .Create(create => create.Action("Device_Create", "Device", new { rollshopId = @Model.RollshopId }))
                .Update(update => update.Action("Device_Update", "Device"))
                .Sort(sort => sort.Add("DeviceID").Ascending())
            )
        )
    </div>
 
</div>

 

My viewmodel page, from which I retrieve all data I need in my view

public class DeviceSearchModel
    {
        public DeviceSearchModel(int rollshopID)
        {
            this.RollshopName = Business.Rollshop.Query(x => x.ID == rollshopID).FirstOrDefault() != null ? Business.Rollshop.Query(x => x.ID == rollshopID).FirstOrDefault().Name : "";
            this.DeviceTypeEnumList = Business.Helper.GetListFromEnum<DeviceTypeDescriptions>();
            this.DeviceList = Business.Device.Query(x => x.RollshopID == rollshopID);
            this.RollshopId = rollshopID;
        }
 
        public string RollshopName { get; private set; }
 
        public List<EnumModel> DeviceTypeEnumList { get; set; }
        public IEnumerable<Business.Device> DeviceList { get; private set; }
        public int RollshopId { get; private set; }
    }

 

I've also the class that own the structure of my dropdown items:

public class EnumModel
        {
            public int Value { get; set; }
            public string Name { get; set; }
        }

 

This is my Enum class:

public enum DeviceTypeDescriptions
    {
        [Display(Name = "Starndard Grinder")]
        StandardGrinder = 0,
        [Display(Name = "Pomini digital texturing")]
        PDT = 1,
        MWGrinder = 2,
        BladeGrinder = 3
    }

 

And this is the method I use to populate my dropdownlist item's from my Enum:

public static List<EnumModel> GetListFromEnum<T>()
        {
            return Enum.GetValues(typeof(T))
                .Cast<T>()
                .Select(x => new EnumModel()
                {
                    Value = Convert.ToInt32(x),
                    Name = x.ToString()
                }).ToList();
        }

 

This is my Device class: in this class I retrieve data which populate the grid:

public sealed class Device : IBusinessDomain
    {
        public int DeviceID { get; internal set; }
        public int RollshopID { get; internal set; }
 
        public string SerialNumber { get; set; }
 
        public int DeviceType { get; set; }
 
        //public DeviceTypeDescriptions DeviceTypeDescription { get; set; }
         
        public Lazy<Business.Rollshop> Rollshop { get; internal set; }
        public Lazy<IEnumerable<Business.Item>> ItemList { get; internal set; }
 
        public static IEnumerable<Device> Query(Expression<Func<Data.MainDB.Device, bool>> where = null)
        {
            using (var db = new Repository())
            {
                IEnumerable<Device> result = db.Device.Enumerate(where).Select(x => (Device) x).ToArray();
                return result;
            }
                 
        }
 
public static explicit operator Device(Data.MainDB.Device arg)
        {
            var value = Mapper.Map<Device>((Data.MainDB.Device) arg);
            return value;
        }
}

 

And this is my database model object:

public partial class Device
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Device()
        {
            this.Item = new HashSet<Item>();
        }
     
        public int ID { get; set; }
        public string SerialNumber { get; set; }
        public int DeviceType { get; set; }
        public System.DateTime CreationDate { get; set; }
        public System.DateTime LastUpdateDate { get; set; }
        public int RollshopID { get; set; }
     
        public virtual Rollshop Rollshop { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Item> Item { get; set; }
    }

 

Ok so now this is my situation. I hope is clear.
The behaviour in this situation is that grid will be populated well on load, but when i click cell to edit content, dropdown does'n appear and i can't edit cell (no textbox also appear) (only for DeviceType column, for SerialNumber column all works).
If in my grid I change bound to foreign key in this way:

 

columns.ForeignKey(p => p.DeviceType, @Model.DeviceTypeEnumList, "Name", "Name");

 

when i load my grid, DeviceType column will remain blank (not bound to it's value), but when i click on this the cell enter correctly in edit mode and show my dropdown. Then if I choose an item in the dropdown, when i click outside cell, this cell return blank (item I choosen is not shown in grid).
I hope is all clear!
Thank

Konstantin Dikov
Telerik team
 answered on 30 Nov 2016
Narrow your results
Selected tags
Tags
+? more
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?