Telerik Forums
UI for ASP.NET MVC Forum
1 answer
83 views
Am I correct in saying that the grid calls the Read operation on its datasource by default?  I am looking at some examples and I can't see where there is an explicit call to read the data from the datasource.  If I am right, is there a way to prevent that and wait for the user to initiate the load?

Thanks
Dimiter Madjarov
Telerik team
 answered on 26 Feb 2013
1 answer
128 views

We are creating an MVC 4 application using the Kendo.Mvc helper assembly. The code is working well; however, we appear to be missing something when we try to obtain a reference to a kendo control.

Example:
Our application has an ActionLink on a toolbar. When the user clicks on the ActionLink, we call into a JS function to validate if the displayed grid has a row selected. Within the function we attempt to obtain a reference to the grid and get the selected row. Unfortunately, the select() function throws an error ("Value is undefined").

I have included the code below. Most of our logic will be based on controls having the ability to communicate with each other from events, etc. Are we able to receive  the functionality using the MVC assembly, or are we only able to use the API when code in JS?

Any comments or assistance would be much appreciated.

Thanks,
Todd

@(Html.Kendo().Grid(Model.Transaction)
.Name("grid")
.Columns(columns => {
    columns.Bound(o => o.EntityId)
        .Hidden().Visible(false);
    columns.Bound(o => o.EntityName)
        .Sortable(true)
        .Title("Entity Name")
        .ClientTemplate(@Html.ActionLink("#=EntityName#", "Details", "Entity", new { id = "entityId" }, null).ToHtmlString().Replace("entityId", "#=EntityId#"));
    columns.Bound(o => o.TransactionType);
    columns.Bound(o => o.Name)
       .ClientTemplate(@Html.ActionLink("#=Name#", "Details", "Engagement", new { id = "engId" }, null).ToHtmlString().Replace("engId", "#=ID#"));
    columns.Bound(o => o.TransactionStatus);
    columns.Bound(o => o.Initiator);
    columns.Bound(o => o.Reason);  
      
})
.Pageable(p => p.PageSizes(true))
.Filterable(filterable => filterable
    .Extra(false)
    .Operators(operators => operators
        .ForString(str => str.Clear()
            .StartsWith("Starts with")
            .IsEqualTo("Is equal to")
            .IsNotEqualTo("Is not equal to")
        ))
    )
.Navigatable()
.Resizable(resize => resize.Columns(true))
.Selectable()
.DataSource(dataSource => dataSource
    .Ajax()
    .Model(model => model.Id(p => p.ID))
    .Read(r => r.Action("Search", "Transaction")))
)
getSelectedRowId: function (gridId) {
            var grid = jQuery(gridId).kendoGrid().data("kendoGrid");
            var row = grid.select();
 
            if (row.length > 0)
                return grid.dataItem(row).id;
            else
                return null;
        }

Nikolay Rusev
Telerik team
 answered on 26 Feb 2013
1 answer
98 views
Hi Kendo,


I tried this on 
http://jsfiddle.net/rusev/E3vYH/ and it works fine. Now I have a listView generated by ListView Kendo Helper and I add a model by calling DataSource.add() method, but when I call DataSource.sync() it doesn't call create and I don't see any http activity on my browser's network tab. I copied the code generated by the kendo helper and pasted it into a test html file and it doesn't work neither. It did add the model to the listView but never calls create. Here is my test file:

<!DOCTYPE html>
<html>
    <head>
        <title>Testing Kendoui dataSource</title>
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
        <script src="http://cdn.kendostatic.com/2012.2.710/js/kendo.all.min.js"></script>
        <script type="text/x-kendo-tmpl" id="template">
            <div data-id = ${CountryCode}> 
 <p>${CountryName}</p>
            </div >
        </script>
        <script>
            $(function () {
                $("#target").kendoListView ({
                    "dataSource": {
                        "transport": {
                            "prefix": "",
                            "read": function () {
                                alert("reading...");
                            },
                            "create": function () {
                                alert("creating...");
                            },
                            "destroy": function () {
                                alert("destroying...");
                            },
                            "update": function () {
                                alert("updating...");
                            }
                        },
                        "type": "aspnetmvc-ajax",
                        "schema": {
                            "data": "Data",
                            "total": "Total",
                            "errors": "Errors",
                            "model": {
                                "id": "SubaccountId",
                                "fields": {
                                    "SubaccountId": {
                                        "type": "number"
                                    },
                                    "CountryCode": {
                                        "type": "string"
                                    },
                                    "CountryName": {
                                        "type": "string"
                                    }
                                }
                            }
                        }
                    },
                    "template": kendo.template($('#template').html()),
                    "selectable": "single"
                });
                $('#addButton').bind("click", function () {
                    var ds = $('#target').data('kendoListView').dataSource;
                    ds.add({

                        SubaccountId: 1,
                        CountryCode: 'US',
                        CountryName: 'United States'

                    });
                    ds.sync();
                });
            });
        </script>
    </head>
    <body>
        <div>
            <button id="addButton">Add Country</button>
        </div>
        <div id="target"></div>
    </body>
</html>

I tried with different jquery and kendo version too. No luck.

How do I make this work.

Thanks

D

Daniel
Telerik team
 answered on 26 Feb 2013
1 answer
229 views
Hi,
I have a box:
@(Html.Kendo().NumericTextBoxFor(m => m.FilterParticipants).Format("n0").Min(1).Decimals(0))
with a required attribute:
[Required(ErrorMessageResourceName = "ValidationRequired", ErrorMessageResourceType = typeof(Resources.Global))]
//[Min(1, ErrorMessageResourceName = "ValidationRequired", ErrorMessageResourceType = typeof(Resources.Global))]

public
int FilterParticipants { get; set; }
and if I clear the box I can still submit the form.
But: I also have a datepicker in the form and if I clear that control and tries to submit, then the validation fires (on both controls).

Regards,
Mattias

Daniel
Telerik team
 answered on 26 Feb 2013
9 answers
309 views
I have a grid that I toggle the visibility of a column on when a button is pushed.

It hides the column header just fine, but with the data it hides is one column to the left.

I'm hiding the column NMFC, and when that is hidden, the NMFC column header disappears.

However, the data under the Weight column ("lbs") is the data that is hidden and the value under NMFC ("test") is now visible underneath the Weight column.

Here's the code for the columns:
columns.Bound(i => i.WeightUOM)
    .EditorTemplateName("ItemGrid_RefUOMListingWeight")
    .Width(50);
columns.Bound(i => i.NMFC).Width(50);
Here's the script code:
var itemGrid = $("#QuoteItemGrid").data("kendoGrid");
itemGrid.hideColumn("NMFC");
I am using a detail template on this grid, so maybe it is throwing the index off by one?  Not sure, but any tip would be helpful.  I can provide more code if needed.  I thought I would try and keep it simple for this first post and only put critical code in.

Thanks!
Jark Monster
Top achievements
Rank 1
 answered on 25 Feb 2013
1 answer
141 views
Hi Experts, 
  Can we display two sets of hierarchy on the same level on a tab strip? Something like  Employee(Main Table)  with Orders received (Hierarchy table 1)  and  orders fullfilled (Hierarchy table 2)?



  
Meera
Top achievements
Rank 1
 answered on 25 Feb 2013
7 answers
139 views
Hi,

Could you please tell me whether desktop applications can be developed using html5 and javascript in Kendo UI?.

Thanks.
Rajesh
Top achievements
Rank 1
 answered on 25 Feb 2013
1 answer
676 views
Hi,

I have editable grid which opens a popup when editing, this is opening a template page.

In this template page I have a kendo datepicker


<div class="editor-label">
    @Html.LabelFor(model => model.DateInvoiced)
</div>
<div class="editor-field">
    @(Html.Kendo().DatePickerFor(model => model.DateInvoiced))
    @Html.ValidationMessageFor(model => model.DateInvoiced)
</div>

It is binding to a viewmodel where the DateInvoiced is a nullable datetime.
When we add a record we don't want to provide this value yet, but when we hit the save button, the kendo datepicker is asking us to provide the value and is making this required.

The model is nullable and does not have required attribute.

        [Display(Name = "Received")]
        public Nullable<DateTime> DateInvoiced { get; set; }

How do we make the datepicker allow blank value?


Petur Subev
Telerik team
 answered on 25 Feb 2013
1 answer
802 views
Hi Experts,
  I had downloaded the KendoGridWithCascadingCombo boxes example posted by admin and used the same concept in my code. I need help with the following

1. I need to show the dropdown text instead of the value on the grid after editing.   The client template does not seem to work for InLineEditing



Here is the code on my razor file 

@using System.Web.Mvc.Html
@using Kendo.Mvc.UI
@model ModelSelectionViewModel

@section Head {
    <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);
            }
        }

        function rowindex(dataItem) {
            var data = $("#ModelSelectionSearchCriteriaList").data("kendoGrid").dataSource.data()
            return data.indexOf(dataItem);
        }



        function filterCategory() {
            return {
                media: $("#Media").data("kendoDropDownList").value()
                            };
        }


        function filterSubCategory() {
            return {
                categoryId: $("#Category").data("kendoDropDownList").value()
            };
        }

    </script>
}

   
<div class="container">
    <div class="row-fluid">
        <div class="span12">
            <ul class="breadcrumb">
                @Html.MvcSiteMap().SiteMapPath()
            </ul>
        </div>
        <!--/span-->
    </div>
    <!--/row-fluid-->
    <div class="row">
        <div class="span12">
            <div class="widget">
                <div class="widget-header">
                    <i class="icon-star"></i>
                    <h3>
                        Model Selection Criteria Panel</h3>
                </div>
                <div class="widget-content">
                    @using (Html.BeginForm("GetData", "ModelSelection"))
                    { 
                        @(Html.Kendo().Grid(Model.ModelSelectionCriteriaList)
                                        .Name("ModelSelectionSearchCriteriaList")
                                    .HtmlAttributes(new { style = "width:100%;" })
                            .Columns(columns =>
                            {
                                columns.Bound(c => c.Media).HeaderHtmlAttributes(new { @title = "Media" }).Width(300).ClientTemplate("#=Media#"  +
                      // "<input type='hidden' name='ModelSelectionSearchCriteriaList[#= rowindex(data)#].Media' value='#= Media #' />"
                      //);
                                columns.Bound(c => c.Category).Title("Category").HeaderHtmlAttributes(new { @title = "Category" }).Width(300);
                      //          .ClientTemplate("#=Category #" + 
                      //  "<input type='hidden' name='ModelSelectionSearchCriteriaList[#= rowindex(data)#].Category' value='#= Category #' />"
                      //);

                                columns.Bound(c => c.SubCategory).Title("SubCategory").HeaderHtmlAttributes(new { @title = "SubCategory" }).Width(300);
                      //          .ClientTemplate("#=SubCategory#" +
                      //  "<input type='hidden' name='ModelSelectionSearchCriteriaList[#= rowindex(data)#].SubCategory' value='#= SubCategory #' />"
                      //);
                                
                              columns.Command( command => { command.Edit(); command.Destroy(); }).Width(200);
                                 })
                            .ToolBar(toolbar =>
                            {
                                toolbar.Create().Text("Add New Criteria");
                            })
                            .Editable(editable => editable
                                .Mode(GridEditMode.InLine)
                                .DisplayDeleteConfirmation(false)
                                )
                            .Scrollable()
                            .DataSource(datasource => datasource
                                .Ajax()
                                .ServerOperation(false)
                                .Events(events => events.Error("error_handler"))
                                .Model(model => model.Id(c => c.Id))
                                    .Create(update => update.Action("EditingInline_Create", "ModelSelection").Type(HttpVerbs.Post))
                                    .Destroy(update => update.Action("EditingInline_Destroy", "ModelSelection").Type(HttpVerbs.Post))
                                    .Update(update => update.Action("EditingInline_Update", "ModelSelection").Type(HttpVerbs.Post))
                                       // .Read(read => read.Action("EditingInline_Read", "ModelSelection").Type(HttpVerbs.Post))
                                    )
                                    )
                                    
                        <input id="save" type="submit" class="btn btn-primary" name="button" value="Search" />
                        @:&nbsp; &nbsp;
                     @Html.ActionLink("Reset Criteria", "Index", "ModelSelection", new { }, new { id = "btnReset", @class = "btn" })
                    }
                </div>
            </div>
        </div>
    </div>
------------------------------------
Editor Templates
1. category.cshtml

@model long
 
    
 @(Html.Kendo().DropDownListFor(m => m)
          .OptionLabel("Select Category...")
          .DataTextField("CategoryText")
          .DataValueField("CategoryId")
          .DataSource(source => {
              source.Read(read =>
              {
                  read.Action("GetModelCategory", "ModelSelection")
                      .Data("filterCategory");
              })
              .ServerFiltering(true);
          })
          .AutoBind(false)
          .CascadeFrom("Media")
    )
     @Html.ValidationMessageFor(m => m)


--------------------------------------------------------------
2. media.cshtml
@model long

    @(Html.Kendo().DropDownListFor(m => m)
          .OptionLabel("Select Media..")
          .DataTextField("MediaText")
                  .DataValueField("MediaId")
          .DataSource(source => {
               source.Read(read => {
                   read.Action("GetModelMedia", "ModelSelection");
               });
          })
    )
     @Html.ValidationMessageFor(m => m)

3. subcategory.cshtml
@model long
 @(Html.Kendo().DropDownListFor(m => m)
          .AutoBind(false)
          .OptionLabel("Select SubCategory...")
          .DataTextField("SubCategoryText")
               .DataValueField("SubCategoryId")
          .DataSource(source => {
              source.Read(read =>
              {
                  read.Action("GetModelSubCategory", "ModelSelection")
                      .Data("filterSubCategory");
              })
              .ServerFiltering(true);
          })
          .CascadeFrom("Category")
    )
     @Html.ValidationMessageFor(m => m)

-----------------------------------------------------------------------------
My Controller code is below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TIMS.Models;
using TIMS.Areas.Alberta.SearchCriteria;
using TIMS.Areas.Alberta.Services;
using TIMS.Services;
using TIMS.Areas.Alberta.ViewModels;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
using TIMS.Controllers;

namespace TIMS.Areas.Alberta.Controllers
{
    public class ModelSelectionController : BaseController
    {
        #region Protected Members
        protected IAlbertaLookupService albertaLkService;
        protected IAlbertaUserSessionService albertaUserSessionService;
        
        
        #endregion

        #region Constructor
        public ModelSelectionController(IAlbertaLookupService albertaLkService, IAlbertaUserSessionService albertaUserSessionService)
        {
            this.albertaLkService = albertaLkService;
            this.albertaUserSessionService = albertaUserSessionService;
        }
#endregion

        public ActionResult Index()
        {
            ModelSelectionViewModel modelSelectionViewModel = new ModelSelectionViewModel();

            List<ModelSelectionSearchCriteria> sessionCriteria = new List<ModelSelectionSearchCriteria>();
            albertaUserSessionService.ModelSelectionSearchCriteriaData = sessionCriteria;
            return View(modelSelectionViewModel);
        }

       
        public ActionResult EditingInline_Read([DataSourceRequest] DataSourceRequest request)
        {
            return Json(albertaUserSessionService.ModelSelectionSearchCriteriaData.ToDataSourceResult(request));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditingInline_Create([DataSourceRequest] DataSourceRequest request, ModelSelectionSearchCriteria criteria)
        {
            
            if (criteria != null && ModelState.IsValid)
            {
                List<ModelSelectionSearchCriteria> sessionCriterias = albertaUserSessionService.ModelSelectionSearchCriteriaData;
                if (sessionCriterias.Count != 0)
                        criteria.Id = sessionCriterias[sessionCriterias.Count -1].Id + 1;
                else
                    criteria.Id = 1;

                sessionCriterias.Add(criteria);
                albertaUserSessionService.ModelSelectionSearchCriteriaData = sessionCriterias;
            }

            return Json(new[] { criteria }.ToDataSourceResult(request, ModelState));
        }
      

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditingInline_Destroy([DataSourceRequest] DataSourceRequest request, ModelSelectionSearchCriteria criteria)
        {
            if (criteria != null )
            {
                List<ModelSelectionSearchCriteria> sessionCriterias = albertaUserSessionService.ModelSelectionSearchCriteriaData;
                int index = 0;
                for (int c = 0; c < sessionCriterias.Count; c++)
                    if (sessionCriterias[c].Id == criteria.Id)
                    {
                        index = c;
                        break;
                    }
                sessionCriterias.RemoveAt(index);
                albertaUserSessionService.ModelSelectionSearchCriteriaData = sessionCriterias;
            }

            return Json(ModelState.ToDataSourceResult());  
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditingInline_Update([DataSourceRequest] DataSourceRequest request, ModelSelectionSearchCriteria criteria)
        {
            if (criteria != null && ModelState.IsValid)
            {
                List<ModelSelectionSearchCriteria> sessionCriterias = albertaUserSessionService.ModelSelectionSearchCriteriaData;
                int index=0;
                for (int c=0; c < sessionCriterias.Count; c++)
                    if (sessionCriterias[c].Id == criteria.Id)
                    {
                        index = c;
                        break;
                    }

                sessionCriterias[index].Media = criteria.Media;
                sessionCriterias[index].Category = criteria.Category;
                sessionCriterias[index].SubCategory = criteria.SubCategory;

                albertaUserSessionService.ModelSelectionSearchCriteriaData = sessionCriterias;
            }
                

            return Json(ModelState.ToDataSourceResult());
        }


        public JsonResult GetModelMedia()
        {
            SelectList medias = albertaLkService.GetModelMediaList();

            return Json(medias.Select( p => new { MediaId = p.Value, MediaText = p.Text}) , JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetModelCategory(long media)
        {
           
           SelectList categories = albertaLkService.GetModelMatrixCategoryList(media);

            return Json(categories.Select(p => new { CategoryId = p.Value, CategoryText = p.Text }), JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetModelSubCategory(long categoryId)
        {
            SelectList subCategories = albertaLkService.GetModelMatrixSubCategoryList(categoryId);
           
            return Json(subCategories.Select(p => new { SubCategoryId = p.Value, SubCategoryText = p.Text }), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetData(ModelSelectionViewModel viewModel)
        {
          List<ModelSelectionSearchCriteria> sessionCriteria = albertaUserSessionService.ModelSelectionSearchCriteriaData;

          
         
            
          return View("result", viewModel);
        }


    }
}

Vladimir Iliev
Telerik team
 answered on 25 Feb 2013
1 answer
326 views
First of all - I'm a newbie to kendo ui and web programming with .NET as a whole so this might be an easy question. With that in mind, here's my problem:

I have a DatePicker and a Grid on a page. Whenever a date is chosen from the DatePicker, it fires an event which queries data from the server and then populates the grid with it. The problem is - it doesn't. The grid stays empty with no errors client or server-side at all.

Here's how I set up the controls:
@(Html.Kendo().DatePicker()
    .Name("DateForReport")
    .Value(DateTime.Now)
    .Events(e =>
        {
            e.Change("getStockInfo");
        })
    )
 
@(Html.Kendo().Grid<Supermarket.Main.Areas.Management.Models.ProductInStockViewModel>()
    .Name("reportsByDateGrid")
    .Columns(columns =>
    {
        columns.Bound(m => m.ProductName);
        columns.Bound(m => m.CategoryName);
        columns.Bound(m => m.Amount);
        columns.Bound(m => m.PricePerUnit);
        columns.Bound(m => m.TotalPrice);
    })
    .Pageable()
    .Sortable()
)
And here's the javascript function that does most of the work:
function getStockInfo() {
    if (this.value() != null) {
        var date = kendo.toString(this.value(), 'd');
        $.ajax({
            type: "get",
            dataType: "json",
            url: "@Url.Action("GetAvailabilitiesByDate")",
            data: { date: date },
            traditional: true,
            success: function (result) {
                if (result.success) {
                    var data = result.data;
                    var newDataSource = new kendo.data.DataSource({
                        data: data,
                        pageSize: 15,
                        schema: {
                            model: {
                                fields: {
                                    ProductName: { type: "string" },
                                    CategoryName: { type: "string" },
                                    Amount: { type: "number" },
                                    PricePerUnit: { type: "number" },
                                    TotalPrice: { type: "number" },
                                }
                            }
                        }
                    });
                    var grid = $("#reportsByDateGrid").data("kendoGrid");
                    grid.setDataSource(newDataSource);
                    grid.refresh();
                } else {
                    alert(result.error);
                }
            },
            error: function () {
                alert("An error has occurred, please try again or inform an administrator!");
            }
        });
    }
}
And here's a sample response that I get:
{"success":true,
"data":[{"ProductName":"Borovec","CategoryName":"Food","Amount":18,"PricePerUnit":1.50,"TotalPrice":27.00},{"ProductName":"Coca-cola","CategoryName":"Beverages","Amount":25,"PricePerUnit":2.50,"TotalPrice":62.50},{"ProductName":"Medenka Lubimka","CategoryName":"Food","Amount":23,"PricePerUnit":1.50,"TotalPrice":34.50}]}
How must I set up the datasource of the grid for this to work?
Lachezar
Top achievements
Rank 1
 answered on 24 Feb 2013
Narrow your results
Selected tags
Tags
+? more
Top users last month
Jay
Top achievements
Rank 3
Bronze
Iron
Iron
yw
Top achievements
Rank 2
Iron
Iron
Stefan
Top achievements
Rank 2
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Bohdan
Top achievements
Rank 2
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Jay
Top achievements
Rank 3
Bronze
Iron
Iron
yw
Top achievements
Rank 2
Iron
Iron
Stefan
Top achievements
Rank 2
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Bohdan
Top achievements
Rank 2
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?