Telerik Forums
Kendo UI for jQuery Forum
3 answers
269 views

Hello,

I'm trying to use kendo grid with angularjs and webApI

From days of typing and searching I want to understand why when posting I get all field as null parameters

I'm still don't understand kendo grid very well

so, I appropriate any help..

 

Model:

    public class EmployeesInfo
    {
        public EmployeesInfo() { }

        //[Required]
        public int ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public int Phone { get; set; }
        public string Job { get; set; }
        public string Department { get; set; }
    }

 

View:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Try</title>
   <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.1.220/styles/kendo.common.min.css">
    <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.412/styles/kendo.rtl.min.css">
    <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.412/styles/kendo.default.min.css">
    <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.412/styles/kendo.mobile.all.min.css">

    <script src="http://kendo.cdn.telerik.com/2019.1.220/js/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.7/angular.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/jszip.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2019.1.220/js/kendo.all.min.js"></script>
    <script src="http://cdn.kendostatic.com/2013.1.319/js/kendo.aspnetmvc.min.js"></script>

</head>
<body>
    <div id="example" ng-app="KendoDemos">
        <h3 style="font-style:italic;color:#F35800"> Information </h3>
        <br />

        <div ng-controller="MyCtrl">
            <kendo-grid
                k-options="mainGridOptions"
                k-data-source="DS"
                k-on-change="onChange(kendoEvent)"
                k-on-save="onSave(kendoEvent)"
                k-selectable="true">
            </kendo-grid>
            
        </div>
    </div>

<script>


        var app = angular.module("KendoDemos", ["kendo.directives"]);
        app.controller("MyCtrl",
            function($scope) {
                $scope.DS = new kendo.data.DataSource({
                    transport: {
                        contentType: "application/json",
                        read: {
                            url: "/api/EmployeesInfoes",
                            dataType: "json",
                            type: "GET"
                        },
                        update: {
                            url: "/api/EmployeesInfoes/PutEmployeesInfo",
                            dataType: "json",
                            type: "PUT"
                        },
                        destroy: {
                            url: "/api/EmployeesInfoes/DeleteEmployeesInfo",
                            dataType: "json",
                            type: "DELETE"

                        },
                        create: {
                            url: "/api/EmployeesInfoes/PostEmployeesInfo",
                            dataType: "json",
                            type: "POST"

                        },
                        parameterMap: function(options, operation) {
                            if (operation !== "read") {
                                console.log(kendo.stringify(options.models));
                                console.log(JSON.stringify(options.models));
                                return { models: kendo.stringify(options.models) };
                            }
                        }
                    },
                    batch: true,
                    pageSize: 8,
                   
                    schema: {
                        
                        model: {
                            id: "ID",
                            fields: {
                                ID: { editable: false, nullable: false, type: "number" },
                                Name: { editable: true, nullable: false,type: "string", validation: { required: true } },
                            }

                        }
                    }

                });

              //  $scope.onSave = function (e,) {

                    // Disable the editor of the "id" column when editing data items
                  //  console.log(e);

               // }

                //$scope.onChange = function(e) {
                 //   alert("on change");
                //};

                $scope.mainGridOptions = {
                    dataSource: $scope.DS,
                 //   dataBound:function(e){
                   //       $('.k-grid-add').unbind("click");
        
                     //     $('.k-grid-add').bind("click", function() {
                       //       console.log("Handle the add button click");

                         // });
                      //},
                    toolbar: ["create"],
                    columns: [
                        { field: "ID", title: "ID", width: "180px" },
                        { field: "Name", title: "Name", width: "180px" },
                        { field: "Age", title: "Age", width: "180px" },
                        { field: "Phone", title: "Phone", width: "180px" },
                        { field: "Job", title: "Job", width: "180px" },
                        { field: "Department", title: "Department", width: "180px" },
                        { command: ["edit", "destroy"], title: "Actions", width: "250px" }
                    ],
                    editable: "popup",
                    pageable: true,
                    filterable: { mode: "row" },


                };

            });


</script>
</body>
</html>  

 

 

 

Controller:

 public class EmployeesInfoesController : ApiController
    {
        private DetailGridContext db = new DetailGridContext();

        // GET: api/EmployeesInfoes
        
        public IQueryable<EmployeesInfo> GetEmployees() {
            return db.Employees;
        }

        // GET: api/EmployeesInfoes/5
        [ResponseType(typeof(EmployeesInfo))]
        public async Task<IHttpActionResult> GetEmployeesInfo(int id)
        {
            EmployeesInfo employeesInfo = await db.Employees.FindAsync(id);
            if (employeesInfo == null)
            {
                return NotFound();
            }

            return Ok(employeesInfo);
        }

        // PUT: api/EmployeesInfoes/5
        [ResponseType(typeof(void))]
        public async Task<IHttpActionResult> PutEmployeesInfo(int id, EmployeesInfo employeesInfo)
        {
            if (!ModelState.IsValid)
            {


                return BadRequest(ModelState);
            }

            if (id != employeesInfo.ID)
            {
                return BadRequest();
            }

            db.Entry(employeesInfo).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmployeesInfoExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/EmployeesInfoes
        [ResponseType(typeof(EmployeesInfo))]
        public async Task<IHttpActionResult> PostEmployeesInfo
            ([FromBody]EmployeesInfo employeesInfo) 
{
            if (!ModelState.IsValid) {

              return BadRequest(ModelState);

                

            }

            db.Employees.Add(employeesInfo);
            await db.SaveChangesAsync();
           
            return CreatedAtRoute("DefaultApi", new { id = employeesInfo.ID }, employeesInfo);
        }

        // DELETE: api/EmployeesInfoes/5
        [ResponseType(typeof(EmployeesInfo))]
        public async Task<IHttpActionResult> DeleteEmployeesInfo(int id)
        {
            EmployeesInfo employeesInfo = await db.Employees.FindAsync(id);
            if (employeesInfo == null)
            {
                return NotFound();
            }

            db.Employees.Remove(employeesInfo);
            await db.SaveChangesAsync();

            return Ok(employeesInfo);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool EmployeesInfoExists(int id)
        {
            return db.Employees.Count(e => e.ID == id) > 0;
        }
    }

 

Alex Hajigeorgieva
Telerik team
 answered on 18 Mar 2019
6 answers
3.5K+ views

Hi, I'm having an issue with my Kendo Grid where when the update event hits my web api controller, the model is showing but all the values are null or 0. I've done this months back with another company and I got it working just fine, but this time around, it's not working.

Here's the relevant snippet on the controller end (and yes, it's hitting right correct controller).

1.[HttpPut]
2.[ResponseType(typeof(spLineItemsGetAllForOrder_Result))]
3.[Route("Orders/UpdateLineItems")]
4.public int UpdateLineItems([FromBody]spLineItemsGetAllForOrder_Result models)
5.{

Even without line 2, the responseType, still doesn't change anything. A long time ago, when we were first having this problem with another company, the key factor was to place the [FromBody] attribute in there. I did that, doesn't help here.

Here's my JS for the grid.

01.$(document).ready(function () {
02.    var crudServiceBaseUrl = "http://localhost:56291/",
03.        dataSource = new kendo.data.DataSource({
04.            transport: {
05.                read: {
06.                    url: crudServiceBaseUrl + 'Orders/GetLineItemsForOrder/' + Cookies.get("ponum"),
07.                    dataType: "json",
08.                    type: 'GET',
09.                    contentType: 'application/json; charset=utf-8'
10.                },
11.                create: {
12.                    url: crudServiceBaseUrl + 'Orders/InsertLineItems/' + Cookies.get("ponum"),
13.                    dataType: "json",
14.                    type: 'POST',
15.                    contentType: 'application/json; charset=utf-8'
16.                },
17.                update: {
18.                    url: crudServiceBaseUrl + "Orders/UpdateLineItems",
19.                    dataType: "json",
20.                    type: "PUT",
21.                    contentType: 'application/json; charset=utf-8'
22.                },
23.                destroy: {
24.                    url: crudServiceBaseUrl + 'Orders/DeleteLineItem/',
25.                    datatype: "json",
26.                    type: 'DELETE',
27.                    contentType: 'application/json; charset=utf-8'
28.                },
29.                parameterMap: function (options, operation) {
30.                    if (operation !== "read" && options.models) {
31.                         
32.                        return { models: kendo.stringify(options.models) };
33.                        
34.                    }
35.                }
36.            },
37.            batch: true,
38.            pageSize: 20,
39.            schema: {
40.                model: {
41.                    id: "LineItemPK",
42.                    fields: {
43.                        LineItemPK: { editable: false, nullable: true },
44.                        Quantity: { editable: true, type: "number", format: "{0:d}" },
45.                        UnitPrice: { editable: true, type: "number", format: "{0:c2}" },
46.                        ExtPrice: { editable: false, type: "number", format: "{0:c2}" },
47.                        ProductFK: { editable: true },
48.                        ProductID: { editable: true },
49.                        UoM: { editable: true },
50.                        InvoiceNum: { editable: true },
51.                        DepFunction: { editable: true },
52.                        CostCenterFK: { editable: false },
53.                        AccountFK: { editable: false },
54.                        OrderFK: { editable: false }
55.                    }
56.                }
57.            }
58.        });
59. 
60.    $("#gridLineItems").kendoGrid({
61.        dataSource: dataSource,
62.        navigatable: true,
63.        pageable: true,
64.        toolbar: [{ name: "create", text: "Insert Line" }, { name: "cancel" }, { name: "save" }],
65.        columns: [
66.            { field: "LineItemPK", title: "LineItemPK", hidden: true },
67.            { field: "Quantity", title: "Qty", validation: { min: 0 } },
68.            { field: "UnitPrice", title: "Unit Price", validation: { min: 0 } },
69.            { field: "ExtPrice", title: "Ext. Price", editable: false, attributes: { "class": "ExtPrice" } },
70.            { field: "ProductFK", title: "Product FK" },
71.            { field: "ProductID", title: "Product ID" },
72.            { field: "UoM", title: "UoM" },
73.            { field: "InvoiceNum", title: "Invoice #" },
74.            { field: "DepFunction", title: "Dep. Funct." },
75.            { field: "CostCenterFK", title: "Cost Center", hidden: false },
76.            { field: "AccountFK", title: "G/L" },
77.            { field: "OrderFK", title: "OrderFK", editable: false, hidden: true },
78.            { command: "destroy", title: " ", width: 120 }
79.        ],
80.        editable: true,
81.        selectable: true
82.    });
83. 
84.});

 

So, this is driving me nuts. I've been playing a lot in the parametermap, such as changing the kendo.stringify to a JSON one, because that worked at my last place...doesn't work here. I then did this, in the model, just for kicks...

01.var models = {
02.    Quantity: 2,
03.    UnitPrice: 15.00,
04.    ExtPrice: 25.00,
05.    BackOrdered: 0,
06.    Received: 0,
07.    InvoiceNum: "IT-101",
08.    AccountFK: 2,
09.    DepFunction: "test dep function",
10.    CostCenterFK: 34,
11.    ProductFK: 2,
12.    OrderFK: 65,
13.    LineItemPK: 3
14.};
15.return JSON.stringify(models);

And that actually brought that "model" over to the web api end with the correct values, however, hard coded. 

 

In my webapiconfig.cs, my Register method is this.

 

01.public static void Register(HttpConfiguration config)
02.{
03.    // Web API configuration and services
04.    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
05.    // Web API routes
06.    config.MapHttpAttributeRoutes();
07. 
08.    config.Routes.MapHttpRoute(
09.        name: "DefaultApi",
10.        routeTemplate: "api/{controller}/{id}",
11.        defaults: new { id = RouteParameter.Optional }
12.    );
13.     
14.}

On line 4, I did change that to, config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); And still, no dice.

I strongly feel it's something on the front end, because when I hard coded that model, the values came over, there's communication - but when I remove it, zilch. I'm hoping someone can help because I've been pulling my hair out on this one. I'm sure it's a matter of me hitting the right combination of stuff.

Thanks in advance.

Alex Hajigeorgieva
Telerik team
 answered on 18 Mar 2019
1 answer
6.8K+ views

Hi there,

I have an array with the list of column names, that needs to be displayed in the grid. 

So, while initializing the grid, I need to loop through each column in the datasource - and if that column is present in the Array, then I need to display it.

For example,

var ColumnNames = ["col1","col3"];

var dataSource = [{"col1": "a", "col2": "1", "col3": "11","col4": "1111"}, {"col1": "b", "col2": "2", "col3": "22","col4": "2222"}, {"col1": "c", "col2": "3", "col3": "33","col4": "3333"}, .....]

 

The grid should display only with the columns present in the array. Here, as shown below:

col1    col3

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

a        11

b        22

c        33

.......

 

The ColumnNames Array and dataSource actually comes from DB, based on the user selection. So, I can not hardcode column names. I tried various options (using column templates, foreach loops for building the model, etc) , but facing one or the other issue. Can someone help me out on this please?

 

Thanks in advance!

 

Regards

Neelima

Viktor Tachev
Telerik team
 answered on 18 Mar 2019
14 answers
196 views

I am doing server validation on my create and update requests. However this causes an issue when updating a recurring event as it triggers both a create and update in some situations.

How can I "merge" 2 requests into 1 e.g. when making a recurrence exception by editing only single event?

Simon
Top achievements
Rank 1
 answered on 16 Mar 2019
3 answers
428 views

Note: the documentation on the Kendo menu provides how to close an item, but not the actual menu itself. 

For example, the menu documentation on the Kendo menu states:
//intialize the menu widget
    $("#menu").kendoMenu();
    // get a reference to the menu widget
    var menu = $("#menu").data("kendoMenu");

    // close the sub menu of "Item1"
    menu.close("#Item1");

gregory
Top achievements
Rank 1
 answered on 16 Mar 2019
3 answers
604 views

There is a bug setting the percentage width for a table within the Kendo editor. 

1. Go to https://demos.telerik.com/kendo-ui/editor/index
2. Under Editor / Basic usage select the Table Wizard Icon and click Table Wizard to bring up the Wizard Dialog
3. You will notice that within this dialog the unit options for width and height are only px and em
4. Within this dialog create a table two columns and four rows
5. Place your cursor in one of the table cells again and click the Table Wizard button again to edit the propertied of the new table
6. The unit options for width and height are still only px and em.  Go ahead and enter 100px into the width field and click Ok on the dialog
7. Once again with you cursor in one of the table cells, click the Table Wizard button again.  Now the units options for all widths and heights for tables and cells are px, em and importantly %
8. If I now create a new table via the Table Wizard the unit options available are px, em and % as expected

I logged a previous, different bug about the Table Wizard in github here: https://github.com/telerik/kendo-ui-core/issues/4390 but have had no response, so is this the correct place for bug reports, or github?

 

 

Ivan Danchev
Telerik team
 answered on 15 Mar 2019
2 answers
87 views

I have created a drop down list embedded within my grid using the demo: https://demos.telerik.com/kendo-ui/grid/editing-custom

For some reason when I select an option within the drop down it doesn't send the data back in a format the grid can use, however the default value (if I don't touch drop down) works just fine.

 

My datasource designed as such: 

schema: {
    model: {
        id: "SwitchID",
        fields: {
            SwitchID: { editable: false, type: "number" },
            switchperson: {
                type: "string",
                validation: { required: true, message: "Switchperson information is required." },
            },
            phoneNum: { type: "string" },
            Location: { type: "string" },                  
            SwitchPersonType: { defaultValue: { switchPersontypeValue: "Employee", switchPersontypeID: 1 } },
            //SwitchPersonType: { type: "string" },
             
        },
    },
},

and the kendo grid:

$("#switchpersonTable").kendoGrid({
    dataSource: switchpersonDataSource,
    scrollable: true,
    sortable: true,
    filterable: false,
    pageable: true,
    toolbar: [{ name: "create", text: "Add Switchperson" }],
    columns: [
        { field: "switchperson", title: "Switchperson", width: "200px" },
        { field: "phoneNum", title: "Phone #", width: "200px" },
        { field: "Location", title: "Location", width: "200px" },
        {
            field: "SwitchPersonType",
            title: "Type",
            width: "150px",
            template: "#=SwitchPersonType.switchPersontypeValue#",
            editor: switchPersonTypeDropDownEditor,
        },
        { command: ["edit", "destroy"], title: " ", width: "200px" },
    ],
    editable: "inline",
});

The editor is the built like this:

$(
    '<input required name="' + options.field + '" data-text-field="switchPersontypeValue" data-value-field="switchPersontypeID" data-bind="value:' +
        options.field +
        '"/>'
)
    .appendTo(container)
    .kendoDropDownList({
        autoBind: false,
        dataSource: {
            data: ddlSwitchPersonType,
        },
    });

and the data source for the drop down list:

var ddlSwitchPersonType = [
    {
        switchPersonTypeID: 1,
        switchPersontypeValue: "Employee",
    },
    {
        switchPersonTypeID: 2,
        switchPersontypeValue: "Contractor",
    },
];

If I create an item in the grid and don't touch the dropdown I get the following back in the e.data:

Location: ""
SwitchID: 0
SwitchPersonType:
            switchPersontypeID: 1
            switchPersontypeValue: "Employee"
__proto__: Object
phoneNum: ""
switchperson: "sdaf"
__proto__: Object

But if I select an option (even the default) the data doesn't come back as an object.  It only sets a field called SwitchPerson 

Location: ""
SwitchID: 0
SwitchPersonType: "Employee"
phoneNum: ""
switchperson: "sdf"
__proto__: Object

Any thoughts on the cause of this?

Thanks in advance

Viktor Tachev
Telerik team
 answered on 15 Mar 2019
3 answers
964 views

I have a page that has a value of fleetId that is set by the Router Object.   I also have a dropdown list that is populated with a datasource.   How can I set the selected value when the page(template) first loads?    It works if I set it to a function in the view model but that creates another set of problems (the onChange won't work)

 

 

 <script id="index" type="text/x-kendo-template">   
  
                       <input data-role="items"    
                              data-bind="source: channelFleets, value: selectedfleet,  
                              events: {
                                change: onChange,                   
                              }" 
                              data-text-field="fleetText"
                              data-value-field="fleetId"          
                         
                 
            />

</script>

---------viewmodel.js-----------------------


var viewModelIndex = kendo.observable({

  fleetId: "",// Set by Router 
  selectedfleet: "",   

// Changing the databinding value to this does work.

 //selectedfleet: function() {

               //    return this.fleetId;             
   //  },
  
  items: [
          { fleetId: "Fleet 1", fleetText: "Fleet 1" },
          { fleetId: "Fleet 2", fleetText: "Fleet 2" },
          { fleetId: "Fleet 3", fleetText: "Fleet 3" }
        ],           


   onChange: function() {              
                 var selectedFleet = this.get("selectedfleet");
                 router.navigate("/operations/fleet/" + selectedFleet);
        },


});


Dimitar
Telerik team
 answered on 15 Mar 2019
1 answer
3.0K+ views

Hi,

We are using Kendo Grid control. I have one field which is editable in the grid. Initially, the grid remains in view mode. There is a button outside the grid. Upon clicking the Edit button, I want to make the whole column in edit mode. I want that the whole column should now have textboxes instead of the label. How can I achieve that in Kendo? I am using Kendo Batch editing, but the problem with inline editing mode is, we can only keep one row in edit mode, not all at once.

I found below thread having the same issue as mine but couldn't find the answer.

https://www.telerik.com/forums/dynamically-changing-template-of-a-column-to-make-it-editable

 

Thanks & Regards,

Ankush Jain

Alex Hajigeorgieva
Telerik team
 answered on 15 Mar 2019
3 answers
2.0K+ views
Hi,

We are using kendo grid in angularjs way and in one column we are showing numbers. There is a button outside the grid and we want that on click of the button, we should be able to edit the numbers, i.e. the column showing numbers, each cell in the column should now have a text box and the number in it. Can you please let me know how can I change the template of the column at run-time (on click of a button) to now have text box and the number that was bound, within the textbox?

Appreciate your quick reply.

Thanks,
Sagar
Alex Hajigeorgieva
Telerik team
 answered on 15 Mar 2019
Narrow your results
Selected tags
Tags
Grid
General Discussions
Charts
Data Source
Scheduler
DropDownList
TreeView
MVVM
Editor
Window
DatePicker
Spreadsheet
Upload
ListView (Mobile)
ComboBox
TabStrip
MultiSelect
AutoComplete
ListView
Menu
Templates
Gantt
Validation
TreeList
Diagram
NumericTextBox
Splitter
PanelBar
Application
Map
Drag and Drop
ToolTip
Calendar
PivotGrid
ScrollView (Mobile)
Toolbar
TabStrip (Mobile)
Slider
Button (Mobile)
Filter
SPA
Drawing API
Drawer (Mobile)
Globalization
LinearGauge
Sortable
ModalView
Hierarchical Data Source
Button
FileManager
MaskedTextBox
View
Form
NavBar
Notification
Switch (Mobile)
SplitView
ListBox
DropDownTree
PDFViewer
Sparkline
ActionSheet
TileLayout
PopOver (Mobile)
TreeMap
ButtonGroup
ColorPicker
Pager
Styling
Chat
MultiColumnComboBox
Dialog
DateRangePicker
Checkbox
Timeline
Drawer
DateInput
ProgressBar
MediaPlayer
ImageEditor
TextBox
OrgChart
Accessibility
Effects
PivotGridV2
Licensing
ScrollView
Switch
TextArea
BulletChart
QRCode
ResponsivePanel
Wizard
CheckBoxGroup
Localization
Barcode
Breadcrumb
Collapsible
MultiViewCalendar
Touch
RadioButton
Stepper
Card
ExpansionPanel
Rating
RadioGroup
Badge
Captcha
Heatmap
AppBar
Loader
Security
TaskBoard
Popover
DockManager
TimePicker
FloatingActionButton
CircularGauge
ColorGradient
ColorPalette
DropDownButton
TimeDurationPicker
ToggleButton
BottomNavigation
Ripple
SkeletonContainer
Avatar
Circular ProgressBar
FlatColorPicker
SplitButton
Signature
Chip
ChipList
VS Code Extension
AIPrompt
PropertyGrid
Sankey
Chart Wizard
OTP Input
SpeechToTextButton
InlineAIPrompt
StockChart
ContextMenu
DateTimePicker
RadialGauge
ArcGauge
AICodingAssistant
SmartPasteButton
PromptBox
SegmentedControl
+? more
Top users last month
Chester
Top achievements
Rank 1
Iron
Simon
Top achievements
Rank 1
Iron
Douglas
Top achievements
Rank 2
Iron
Iron
SUNIL
Top achievements
Rank 3
Iron
Iron
Iron
Marco
Top achievements
Rank 3
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Chester
Top achievements
Rank 1
Iron
Simon
Top achievements
Rank 1
Iron
Douglas
Top achievements
Rank 2
Iron
Iron
SUNIL
Top achievements
Rank 3
Iron
Iron
Iron
Marco
Top achievements
Rank 3
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?