Telerik Forums
UI for ASP.NET MVC Forum
6 answers
275 views
Hi,

Please can someone help as I cannot get the grid to display any results?

I have adapted the code from the grid example in the installed demos but cant get it to work. Please see my code below.

View:

@(Html.Kendo().Grid<StatusPage.Models.Appliance>()
      .Name("grid")
      .Columns(columns =>
      {
          columns.Bound(p => p.Title);
          columns.Bound(p => p.CurrentStatus).Width(100);
          columns.Command(command => { command.Edit(); command.Destroy(); }).Width(172);
      })
      .ToolBar(tools =>
      {
          tools.Create();
      })
      .Sortable()
      .Pageable()
      .Filterable()
      .DataSource(dataSource =>
          dataSource
            .WebApi()
            .Model(model =>
            {
                model.Id(p => p.Id);
            })
            .Events(events => events.Error("error_handler"))
                    .Read(read => read.Url(Url.HttpRouteUrl("Appliance", new { controller = "Appliances" })))
                    .Create(create => create.Url(Url.HttpRouteUrl("Appliance", new { controller = "Appliances" })))
                    .Update(update => update.Url(Url.HttpRouteUrl("Appliance", new { controller = "Appliances", id = "{0}" })))
                    .Destroy(destroy => destroy.Url(Url.HttpRouteUrl("Appliance", new { controller = "Appliances", id = "{0}" })))
      )
)
 
<script>
function error_handler(e) {
    var errors = $.parseJSON(e.xhr.responseText);
 
    if (errors) {
        alert("Errors:\n" + errors.join("\n"));
    }
}
</script>

Controller:
public class AppliancesController : BaseApiController
    {
        public AppliancesController(IRepository repo)
            : base(repo)
        {
        }
 
        public DataSourceResult Get([System.Web.Http.ModelBinding.ModelBinder(typeof(WebApiDataSourceRequestModelBinder))]DataSourceRequest request)
        {
            //var appliances = TheRepository.GetAppliances().ToList()
            //                    .Select(m => TheModelFactory.Create(m));
 
            var appliances = new List<Appliance>() { new Appliance() { Title = "Appliance 1", CurrentStatus = 2 } };
 
            return appliances.ToDataSourceResult(request);
        }
 
        public HttpResponseMessage Get(int appId)
        {
            try
            {
                var entity = TheRepository.GetAppliance(appId);
                if (entity == null) return Not_Found();
 
                return Request.CreateResponse(HttpStatusCode.OK,
                    TheModelFactory.Create(entity));
            }
            catch
            {
                // TODO logging
            }
 
            return Bad_Request();
        }
 
        public HttpResponseMessage Post([FromBody] Appliance model)
        {
            try
            {
                if (!ModelState.IsValid) return Bad_Request();
                model.CurrentStatus = (int)StatusType.Operational;
                model.LastUpdated = DateTime.Now;
 
                if (TheRepository.Insert(model) && TheRepository.SaveAll())
                {
                    return Request.CreateResponse(HttpStatusCode.Created, TheModelFactory.Create(model));
                }
            }
            catch
            {
                // TODO logging
            }
 
            return Bad_Request();
        }
 
        [HttpDelete]
        public HttpResponseMessage Delete(int appId)
        {
            try
            {
                var entity = TheRepository.GetAppliance(appId);
                if (entity == null) return Not_Found();
 
                if (TheRepository.DeleteAppliance(entity) && TheRepository.SaveAll())
                {
                    return Request.CreateResponse(HttpStatusCode.OK);
                }
            }
            catch
            {
                // TODO logging
            }
 
            return Bad_Request();
        }
 
        [HttpPut]
        [HttpPatch]
        public HttpResponseMessage Patch(int appId, [FromBody] Appliance model)
        {
            try
            {
                if (!ModelState.IsValid || appId != model.Id)
                    return Bad_Request();
 
                if (TheRepository.UpdateAppliance(model) && TheRepository.SaveAll())
                {
                    return Request.CreateResponse(HttpStatusCode.OK);
                }
            }
            catch (Exception ex)
            {
                return Bad_Request(ex);
            }
 
            return Bad_Request();
        }
    }

The grid is displayed and the web api controller GET is being called and is returning the DataSourceResult and no rows are displayed.

If anyone can help I would be grateful. Thanks in advance.
chris
Top achievements
Rank 1
 answered on 22 Aug 2014
1 answer
114 views
Hi,

I cannot figure out how to get access to dropdown selected item in the update procedure.

See attached files.

Regards


Petur Subev
Telerik team
 answered on 22 Aug 2014
1 answer
2.4K+ views
Hi ,

            I'm trying to add custom delete command in the grid , When clicking the delete button I have to call a popup window with textbox entering reason to delete the record and save the reason in different table and delete the selected record from the grid... I'm not able to create a delete popup. Any help appreciated. Thank you


<h2>Delete Selected Transaction</h2>
<br />
 
@* The DIV where the Kendo grid will be initialized *@
<div id="grid"></div>
 
 
<script id="popup_editor" type="text/x-kendo-template">
<p>  <h4> Enter Reason to Delete this Transaction</h4></p>
<div class="k-edit-label"><label for="Notes">Notes</label></div> 
<textarea name="Notes" data-bind="value: Notes" class="k-textbox" required validationMessage="Notes is required." style="height: 100px;"></textarea>
 
</script>
 
 
 
 
<script>
 
    $(function () {
        $("#grid").kendoGrid({
            dataSource: {
                transport: {
                    read: {
                      url: "GetJournalsFromLoadByID"
                      contentType: "application/json; charset=utf-8",
                      type: "POST"
                      cache: true,
                      data: {
                                tkey: @Request["tkey"]
                            }                      
                    },
 
                     update: {
                    url: "@Url.Action("EditingPopup_Delete","Journals")",                   
                    type: "POST",                                         
                    complete: function(e) {
                        alert("Successfully Deleted - Transactionn");
                        $("#grid").data("kendoGrid").dataSource.read();
                        },
                    error: function (e) {
                       alert("Manage: DeleteTransaction -> Ajax Error!");
                    }
                },
 
 
                    parameterMap: function (data, operation) {                     
 
                         if (operation != "read") {
                        var result = {};
                            for (var i = 0; i < data.models.length; i++) {
                            var tk = data.models[i]; 
                            var c = new Date(tk.CreatedDate);
                            tk.CreatedDate = kendo.toString(new Date(c), "F"); 
                            for (var member in tk) {
                                result["newTkey[" + i + "]." + member] = tk[member];
                            }
                        }
                        return result;
                    }
                    else {
                         return JSON.stringify(data)
                    }
 
 
                    }                   
              },
                schema: {
                    data: "Data",
                    total: "Total",
                    model: {
                    id: "TRANSACTION_KEY",
                    fields: {
                        TRANSACTION_KEY: { editable: false, nullable: true },
                        Notes: { editable: true, validation: { required: true } }
 
                    }
                }              
 
                     
                                       
 
                },
                pageSize: 1000,
                serverPaging: true,
                serverFiltering: true,
                serverSorting: true
            },
            groupable: true,
            columnMenu: true,
            filterable: true,
            sortable: true,
            pageable: true,
            columns: [
            { field: "TRANSACTION_KEY", title: "TRANSACTION_KEY", width: "100px" },
            { field: "FISCAL_YEAR ", title: "FISCAL_YEAR", width: "150px" },
            { field: "ACCOUNTING_PERIOD", title: "ACCOUNTING_PERIOD", width: "150px" },
            { field: "Notes", width:"250px" },
            { command: ["edit"], title:"Update Delete Reason", width:"200px"}],     //["edit","destroy"]
            editable: {
            mode: "popup",
            template: kendo.template($("#popup_editor").html())
        }
        });
    });
 
</script>
 
 
 
<script type="text/kendo-template" id="message">
<div class="k-widget k-tooltip k-tooltip-validation k-invalid-msg field-validation-error" style="margin: 0.5em; display: block; " data-for="#=field#" data-valmsg-for="#=field#" id="#=field#_validationMessage">
            <span class="k-icon k-warning"> </span>#=message#<div class="k-callout k-callout-n"></div></div>
</script>
 
<script type="text/javascript">
    var validationMessageTmpl = kendo.template($("#message").html());
 
    function error(args) {
        if (args.errors) {
            var grid = $("#grid").data("kendoGrid");
            grid.one("dataBinding", function (e) {
                e.preventDefault();   // cancel grid rebind if error occurs                            
 
                for (var error in args.errors) {
                    showMessage(grid.editable.element, error, args.errors[error].errors);
                }
            });
        }
    }
 
    function showMessage(container, name, errors) {
        //add the validation message to the form
        container.find("[data-valmsg-for=" + name + "],[data-val-msg-for=" + name + "]")
        .replaceWith(validationMessageTmpl({ field: name, message: errors[0] }))
    }
</script>
Dimo
Telerik team
 answered on 22 Aug 2014
3 answers
227 views
I have a hierarchal grid that's mostly doing what I want, however, paging and scrolling are not working as expected.  I'm using AJAX binding.  It doesn't seem to matter what I set pageSize to in the DataSource section; the presentation doesn't change much, only the number of page buttons for example.  In my current scenario I have 12 rows in the 2nd level grid, and a pageSize of 6.  Scrolling is turned on.  The grid allows me to scroll through all 12 rows, but what I expected was that I could use the page buttons to advance.  I tried turning scrolling off and it kept right on scrolling the entries.  This is very curious, and not at all what I expected.  The following shows my grid markup (RAZOR format):

@(Html.Kendo().Grid(Model)
    .Name("BatchGrid")
    .Pageable()
    .Sortable()
    .Scrollable()
    .HtmlAttributes(new { style = "height:525px; width:1200px" })
    .Columns(columns =>
                {
                    columns.Bound(b => b.BatchID)
                                        .Width("300px")
                                        .Title("Batch ID")
                                        .Visible(false);
                    columns.Bound(b => b.ShortBatchID)
                                        .Width("100px")
                                        .Title("Batch ID");
                    columns.Bound(b => b.HasErrorTransaction)
                                        .Width("50px")
                                        .Title("Err").Visible(false);
                    columns.Command(c => c.Custom("Post Batch")
                                          .Click("onClickPostBatch")
                                          .HtmlAttributes(new { style = "width:100px;" }));
                    columns.Bound(b => b.Created_Emp_Name)
                                        .Width("200px")
                                        .Title("Created Employee");
                    columns.Bound(b => b.Transmitted_DateTime)
                                        .Width("175px")
                                        .Format("{0:MM/dd/yyyy hh:mm tt}")
                                        .Title("Transmitted");
                    columns.Bound(b => b.Completed_DateTime)
                                        .Width("175px")
                                        .Format("{0:MM/dd/yyyy hh:mm tt}")
                                        .Title("Completed");
                    columns.Command(c => c.Custom("Delete Batch")
                                          .Click("onClickDeleteBatch")
                                          .HtmlAttributes(new { style = "width:100px;" }));
                }
            )
        .DataSource(dataSource => dataSource
            .Ajax()
            .Sort(sort => sort.Add("HasErrorTransaction").Ascending()) // <-- initial sort
            .PageSize(12)
            .Read(read => read.Action("FetchBatchCollection", "Home").Data("addlData"))
            .ServerOperation(false)
        )
        .Events(events => events.DataBound("onBatchGridDataBound")
                                .DetailExpand("onBatchGridExpand"))
        .ClientDetailTemplateId("transactions")
    )
 
<!-- Nested grid for transaction object, member of BatchHeader.TranCollection
     There can be many ITransaction objects per BatchHeader -->
<script id="transactions" type="text/kendo-tmpl">
    @(Html.Kendo().Grid<ROAMTranReview.ROAMHostSvc.TransactionBase>()
            .Name("TranGrid_#=BatchID#")  // makes the sub-grid name unique so that it will be displayed on each child row.
            .HtmlAttributes(new { style = "height:535px; width:1400px" })
            .Columns(columns =>
            {
                columns.Bound(b => b.BatchID)
                                    .Visible(false);
                columns.Bound(b => b.TransactionType)
                                    .Visible(false);
                columns.Bound(b => b.ID)
                                    .Width("300px")
                                    .Title("Transaction ID")
                                    .Visible(false);
                columns.Bound(b => b.ShortTranID)
                                    .Width("100px")
                                    .Title("Tran ID");
                columns.Command(c => c.Custom("View Transaction")
                                      .Click("onClickViewTransaction")
                                      .HtmlAttributes(new { style = "width:100px;" }));
                columns.Bound(b => b.TranTypeDisplayText)
                                    .Width("100px")
                                    .Title("Type");
                columns.Bound(b => b.ItemID)
                                    .Width("100px")
                                    .Title("Item ID");
                columns.Bound(b => b.ItemDescription)
                                    .Width("300px")
                                    .Title("Item Description");
                columns.Bound(b => b.Quantity)
                                    .Width("50px")
                                    .Title("Qty");
                columns.Bound(b => b.WorkOrderTask)
                                    .Width("100px")
                                    .Title("Workorder");
                columns.Bound(b => b.EmployeeName)
                                    .Width("200px")
                                    .Title("Employee");
                columns.Command(c => c.Custom("Delete Transaction")
                                      .Click("onClickDeleteTransaction")
                                      .HtmlAttributes(new { style = "width:155px;" }));
                columns.Bound(b => b.PostingFlagDisplayText)
                                    .Width("150px")
                                    .Title("Posting Flag");
           })
           .Scrollable()
           .Pageable()
           .DataSource(dataSource => dataSource
                .Ajax()
                .PageSize(6)
                .Read(read => read.Action("FetchTransactionCollection", "Home", new { batchID = "#=BatchID#" }))
            )
            .Events(events => events.DataBound("onTranGridDataBound")
                                .DetailExpand("onTranGridExpand"))
            .ToClientTemplate()
    )
 
</script>
Dimo
Telerik team
 answered on 22 Aug 2014
22 answers
1.1K+ views
I recently updated all my Telerik controls (using the control panel) and now projects that were previously created with the Kendo UI Visual Studio extension will not permit me to upgrade. The error I get is "No Projects Selected" and then instructions to go back and select at least one project. The Kendo upgrade item in the right click menu does not show up at all, so this errors is coming from running the command from the Telerik tool bar.  All of the extensions are updated to most current via the control panel and via a check for extension updates in Visual Studio.  Creating a new C# Kendo UI MVC Application works fine and the project is manageable by the extension
Andreas Schneider
Top achievements
Rank 1
 answered on 22 Aug 2014
2 answers
104 views
http://demos.telerik.com/aspnet-mvc/scheduler/index

Select Month
Double click "HR seminar preparation" on Wednesday June 5th.
Repeat = Daily
End = On 6/12/2013

Delete the current occurrence for "HR seminar preparation" on June 09
Edit the current occurrence for "HR seminar preparation" on June 10 End Date to 6/11/2013 12:00 PM (this meeting is a two day event now)
Edit the current occurrence for "HR seminar preparation" on June 11 End Date to 6/12/2013 12:00 PM (this meeting is a two day event now)
Edit the current occurrence for "HR seminar preparation" on June 10 Owner from Alex to Charlie

Note that the current occurrence for "HR seminar preparation" on June 10 disappears.
I switched to Week and Day view too and its not there either..
     
Edward
Top achievements
Rank 1
 answered on 21 Aug 2014
3 answers
48 views
for ScatterLine chart, if the baseUnit is "weeks", how could I set the seekStartDay to Monday?  I try 
             xAxis:{
                baseUnit:"weeks",
                min: new Date('2014-01-25'),
                weekStartDay:1
              },

But it did not work for ScatterLine chart.  The start day is always Sunday.  
Hristo Germanov
Telerik team
 answered on 21 Aug 2014
3 answers
353 views
I was wondering whether Telerik intended to produce VB.net examples as they did with the AJAX ASP.NET tools?

Translating controller code is easy with the Telerik Code Translator, but the translator doesn't understand Razor markup and therefore translation can be a bit hit-or-miss and is time consuming.

It would be good to know if there is no intention to do this in the future.

Many thanks
Richard
Sebastian
Telerik team
 answered on 21 Aug 2014
1 answer
133 views
Having learnt that Gantt doesn't (yet) support passing models to views I am attempting to engineer a datasource/service driven Gantt chart.

View is:
<div class="gantt-wrapper">
    @(Html.Kendo().Gantt(Of IMS_2.Models.Task, IMS_2.Models.Dependency)().Name("gantt") _
    .Columns(Sub(columns)
                     columns.Bound(Function(c) c.ID).Title("ID").Width(50)
                     columns.Bound("title").Editable(True).Sortable(True)
                     columns.Bound("start").Title("Start Time").Format("{0:MM/dd/yyyy}").Width(100).Editable(True).Sortable(True)
                     columns.Bound("end").Title("End Time").Format("{0:MM/dd/yyyy}").Width(100).Editable(True).Sortable(True)
             End Sub) _
          .Views(sub(views)
                         views.DayView()
                         views.WeekView(Function(weekView) weekView.Selected(True))
                         views.MonthView()
                         End Sub) _
                         .DataSource(Function(d) d.Read(Function(read) read.Action("ReadTasks", "Gantt")).Model(Sub(m)
                                                                                                                        m.Id(Function(f) f.ID)
                                                                                                                        m.ParentId(Function(f) f.ParentID)
                                                                                                                        m.OrderId(Function(f) f.OrderID)
                                                                                                                        m.Field(Function(f) f.Expanded)            
                                                                                                                End Sub)))
</div>

The following is rendered but no gantt chart is displayed:
<div class="gantt-wrapper">
    <div data-role="gantt" id="gantt"></div><script>
    jQuery(function(){jQuery("#gantt").kendoGantt({"columns":[{"title":"ID","width":50,"sortable":true,"field":"ID"},{"title":"Project Name","editable":true,"sortable":true,"field":"title"},{"title":"Start Time","format":"{0:MM/dd/yyyy}","width":100,"editable":true,"sortable":true,"field":"start"},{"title":"End Time","format":"{0:MM/dd/yyyy}","width":100,"editable":true,"sortable":true,"field":"end"}],"views":[{"type":"day"},{"selected":true,"type":"week"},{"type":"month"}],"dataSource":{"type":(function(){if(kendo.data.transports['aspnetmvc-ajax']){return 'aspnetmvc-ajax';} else{throw new Error('The kendo.aspnetmvc.min.js script is not included.');}})(),"transport":{"read":{"url":"/Gantt/ReadTasks"},"prefix":""},"schema":{"data":"Data","total":"Total","errors":"Errors","model":{"id":"ID","fields":{"ID":{"type":"number"},"title":{"from":"Title","type":"string"},"start":{"from":"Start","type":"date"},"end":{"from":"End","type":"date"},"parentId":{"from":"ParentID","type":"number"},"orderId":{"from":"OrderID","type":"number"},"percentComplete":{"from":"PercentComplete","type":"number"},"expanded":{"from":"Expanded","type":"boolean"},"summary":{"from":"Summary","type":"boolean"}}}}},"dependencies":{"type":(function(){if(kendo.data.transports['aspnetmvc-ajax']){return 'aspnetmvc-ajax';} else{throw new Error('The kendo.aspnetmvc.min.js script is not included.');}})(),"transport":{"read":{"url":""},"prefix":""},"schema":{"data":"Data","total":"Total","errors":"Errors","model":{"fields":{"DependencyID":{"type":"number"},"PredecessorId":{"type":"number"},"SuccessorId":{"type":"number"},"Type":{"type":"number"}}}}}});});
</script>
</div>
        </div>

The controller datasource service is not being called (no breakpoints are hit).  Any help gratefully received!
Thanks
Richard
Top achievements
Rank 1
 answered on 21 Aug 2014
1 answer
213 views
My scenario is simple.  A user selects a course from the dropdown and uses the fileupload to select 1 or more files.  The user hits submit and the file is saved in a file directory along with file data saved in the database.

My dropdown:

        @Html.LabelFor(m => m.selectedCourseID)
        @Html.DropDownListFor(m => m.selectedCourseID, Model._courses)


If I use just a regular <input id="FilePath" title="upload a image" type="file" name="file" />, everything saves correctly.   But, I'd rather use the Kendo Upload.  If I add this:

     <div class="demo-section">
                    @(Html.Kendo().Upload()
                    .Name("Images")
                    )
                </div>

I get the following runtime error:

The ViewData item that has the key 'selectedCourseID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.



My viewmodel:

        [Display(Name = "Select a course...")]
        public int selectedCourseID { get; set; }


        public IEnumerable<SelectListItem> _courses { get; set; }   



Is this enough information or should I send you information?   Thanks in advance.


Dimiter Madjarov
Telerik team
 answered on 21 Aug 2014
Narrow your results
Selected tags
Tags
Grid
General Discussions
Scheduler
DropDownList
Chart
Editor
TreeView
DatePicker
ComboBox
Upload
MultiSelect
ListView
Window
TabStrip
Menu
Installer and VS Extensions
Spreadsheet
AutoComplete
TreeList
Gantt
PanelBar
NumericTextBox
Filter
ToolTip
Map
Diagram
Button
PivotGrid
Form
ListBox
Splitter
Application
FileManager
Sortable
Calendar
View
MaskedTextBox
PDFViewer
TextBox
Toolbar
MultiColumnComboBox
Dialog
DropDownTree
Checkbox
Slider
Switch
Notification
Accessibility
ListView (Mobile)
Pager
ColorPicker
DateRangePicker
Wizard
Security
Styling
Chat
DateInput
MediaPlayer
TileLayout
Drawer
SplitView
Template
Barcode
ButtonGroup (Mobile)
Drawer (Mobile)
ImageEditor
RadioGroup
Sparkline
Stepper
TabStrip (Mobile)
GridLayout
Badge
LinearGauge
ModalView
ResponsivePanel
TextArea
Breadcrumb
ExpansionPanel
Licensing
Rating
ScrollView
ButtonGroup
CheckBoxGroup
NavBar
ProgressBar
QRCode
RadioButton
Scroller
Timeline
TreeMap
TaskBoard
OrgChart
Captcha
ActionSheet
Signature
DateTimePicker
AppBar
BottomNavigation
Card
FloatingActionButton
Localization
MultiViewCalendar
PopOver (Mobile)
Ripple
ScrollView (Mobile)
Switch (Mobile)
PivotGridV2
FlatColorPicker
ColorPalette
DropDownButton
AIPrompt
PropertyGrid
ActionSheet (Mobile)
BulletGraph
Button (Mobile)
Collapsible
Loader
CircularGauge
SkeletonContainer
Popover
HeatMap
Avatar
ColorGradient
CircularProgressBar
SplitButton
StackLayout
TimeDurationPicker
Chip
ChipList
DockManager
ToggleButton
Sankey
OTPInput
ChartWizard
SpeechToTextButton
InlineAIPrompt
TimePicker
StockChart
RadialGauge
ContextMenu
ArcGauge
AICodingAssistant
+? more
Top users last month
Bohdan
Top achievements
Rank 3
Iron
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Elliot
Top achievements
Rank 1
Iron
Iron
Iron
Sunil
Top achievements
Rank 1
Cynthia
Top achievements
Rank 1
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Bohdan
Top achievements
Rank 3
Iron
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Elliot
Top achievements
Rank 1
Iron
Iron
Iron
Sunil
Top achievements
Rank 1
Cynthia
Top achievements
Rank 1
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?