Telerik Forums
UI for ASP.NET MVC Forum
3 answers
116 views

Hi

i have download nice Tools knedo ui and try to use Grid in MVC - it works fine but i have two problems and i don't know how to resolve them 

1. i can't get filed from joined table to let me display text filed in my grid as example (Supplier table is joined to Products table in SupplierID) but i can't view CompanyName in my grid i try it as:

columns.Bound(o => o.Supplier).ClientTemplate("#=Supplier.CompanyName#").Width(160);

but it make grid now working ?

 2. i need to insert dropdownlist in my grid that contain Supplier  ID and "CompanyName" but it now working for me too i try add:

model.Field(o => o.SupplierID).DefaultValue(ViewData["defaultCategory"] as AjaxHierarchyEditing.Models.Supplier);

 and fill ViewData in Home Controller

 my full Code is:

HTML Code:

<div class="k-rtl">
 
    <script type="text/kendo" id="productsTemplate">
        @(Html.Kendo().Grid<ProductViewModel>()
            .Name("Categories_#=CategoryID#")
            .Columns(columns =>
            {
 
                columns.Bound(o => o.ProductName).Width(101).Title("اسم الصنف");
                columns.Bound(o => o.UnitPrice).Width(140).Title("سعر الوحده").HeaderHtmlAttributes(new { style = "font-size:12pt;" });
                columns.Bound(o => o.QuantityPerUnit).Width(200).Title("الكميه للوحده");
                columns.Bound(o => o.ReorderLevel).Width(200).Title("مستوي اعاده الطلب");
                columns.Bound(o => o.Supplier).ClientTemplate("#=Supplier.CompanyName#").Width(160);
                columns.Command(command =>
                {
                    command.Edit();
                    command.Destroy();
 
                });
            })
            .ToolBar(tools => tools.Create().Text("اضافه صنف جديد"))
            .Editable(editable => editable.Mode(GridEditMode.PopUp))
            .Pageable()
            .Sortable()
            .Filterable()
            .DataSource(source => source
            .Ajax()
            .Model(model =>
                {
                    model.Id(o => o.ProductID);
                    model.Field(o => o.ProductID).Editable(false);
                    model.Field(o => o.SupplierID).DefaultValue(ViewData["defaultCategory"] as AjaxHierarchyEditing.Models.Supplier);
                })
            .Events(events => events.Error("error_handler"))
            .Read(read => read.Action("Read_Product", "products", new { id = "#=CategoryID#" }))
            .Update(update => update.Action("Update_Product", "products"))
            .Create(create => create.Action("Create_Product", "products", new { id = "#=CategoryID#" }))
            .Destroy(destroy => destroy.Action("Destroy_Product", "products")))
            .ToClientTemplate()
        )
    </script>
</div>
 
 
 
<div class="k-rtl">
    @(Html.Kendo().Grid<Category>()
    .Name("Categories_")
    .Columns(columns =>
    {
        columns.Bound(e => e.CategoryName).Width(200).Title("اسم المجموعه"); ;
        columns.Bound(e => e.Description).Width(400).Title("الوصف"); ;
        columns.Command(command =>
            {
                command.Edit();
                command.Destroy();
            });
    })
 
    .ToolBar(tools => tools.Create().Text("اضافه مجموعه جديده"))
    .Editable(editable => editable.Mode(GridEditMode.PopUp))
    .Pageable().Sortable().Filterable()
    .DataSource(source => source.Ajax()
    .Model(model =>
       {
            model.Id(e => e.CategoryID);
       })
     .Events(events => events.Error("error_handler"))
     .Read(read => read.Action("Read_category", "kinds"))
     .Update(update => update.Action("Update_category", "kinds"))
     .Create(create => create.Action("Create_category", "kinds"))
     .Destroy(destroy => destroy.Action("Destroy_category", "kinds")))
     .ClientDetailTemplateId("productsTemplate")
    )
</div>
 
<script type="text/javascript">
    function error_handler(e) {
        productsTemplate
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            alert(message);
        }
    }
</script>

Home Controller Code:

public ActionResult Index()
{
    PopulateCategories();
    return View();
}
  
private void PopulateCategories()
{
    ViewData["defaultCategory"] = new SelectList(context.Suppliers, "SupplierID", "CompanyName");
}

Product Controller Read Code:

public ActionResult Read_Product([DataSourceRequest] DataSourceRequest request, int id)
{
    return Json(context.Products.Where(i => i.CategoryID == id).ToDataSourceResult(request, e => new ProductViewModel
    {
 
        ProductID = e.ProductID,
        ProductName = e.ProductName,
        QuantityPerUnit = e.QuantityPerUnit,
        UnitPrice = e.UnitPrice,
        ReorderLevel = e.ReorderLevel,
        SupplierID = e.SupplierID,
 
    }));
}
 ProductViewModel Code:

    public ProductViewModel()
    {
        this.Order_Details = new HashSet<Order_Detail>();
        this.units = new HashSet<unit>();
    }
 
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public Nullable<int> SupplierID { get; set; }
    //public Nullable<int> CategoryID { get; set; }
    public string QuantityPerUnit { get; set; }
    public Nullable<decimal> UnitPrice { get; set; }
    public Nullable<short> UnitsInStock { get; set; }
    public Nullable<short> UnitsOnOrder { get; set; }
    public Nullable<short> ReorderLevel { get; set; }
    //public bool Discontinued { get; set; }
    //public string EAN13 { get; set; }
 
    public virtual Category Category { get; set; }
    public virtual ICollection<Order_Detail> Order_Details { get; set; }
    public virtual Supplier Supplier { get; set; }
    public virtual ICollection<unit> units { get; set; }
}
 

so please how can i resolve those problems ?

Ahmed
Top achievements
Rank 2
 answered on 15 Apr 2015
2 answers
176 views

Hi

Please sir, i have add barcode in my view and it works as code:

 

@(Html.Kendo().Barcode()
    .Name("manchego")
    .Value("2346722")
    .Encoding(BarcodeSymbology.EAN8)
    .Width(200)
    .Height(100)
)

now i need to pass value to barcode from EmployeeViewModel for each employee to let me view them in my page as example :

   <ul id="dairy">
            <li>
@* here pass value for employee 1 *@
@(Html.Kendo().Barcode().Name("manchego").Value("2346722").Encoding(BarcodeSymbology.EAN8).Width(200).Height(100))
            </li>
            <li>
@* here pass value for employee 2 *@
@(Html.Kendo().Barcode().Name("mascarpone").Value("Mascarpone").Encoding(BarcodeSymbology.Code128).Width(200).Height(100))
            </li>
            <li>
@* here pass value for employee 3 *@
@(Html.Kendo().Barcode().Name("gudbrands").Value("CHEESE").Encoding(BarcodeSymbology.Code39).Width(200).Height(100))
            </li>
        </ul>

and ect ..... for any other employee

 so please how can i do that ?

Ahmed
Top achievements
Rank 2
 answered on 15 Apr 2015
4 answers
137 views

Could I get another SignalR example, where the scheduler hub is called from another controller? Here's my workflow:

1. big screen shows day's schedule

2. user schedules work order from other page

3. after saving change, call Hub.Clients.All.update(updatedItem)

4. big screen scheduler updates

 

Scott
Top achievements
Rank 1
 answered on 15 Apr 2015
5 answers
278 views

I have the following code that I am trying to use to delete an item in the database when someone clicks the delete button:
 

<script id="treeview-template" type="text/kendo-ui-template">
         #: item.name #
         <a href="javascript:void(0)" class='btn-sm btn-danger' onclick="DeleteNode(@item.id)">x</a>
 </script>
 @Html.Kendo().TreeView().Name("Categories").ExpandAll(true).Template("treeview-template").DataSource(dataSource => dataSource
.Model(model => model
.Id("id")
         .HasChildren("hasChildren")
         )
           .Read(read => read.Action("GetCategories", "Categories"))).DataTextField("name").DragAndDrop(true).Checkboxes(true).Events(events => events.Change("onChange").Select("onSelect").Check("onCheck").Collapse("onCollapse").Expand("onExpand").DragStart("onDragStart").Drag("onDrag").Drop("onDrop").DragEnd("onDragEnd"))

The issue I'm having is that the field I'm trying to pass to the function, @item.id, is causing the exception: "The name 'item' does not exist in the current context." How can I format the code so this works?

Thanks.

Laurie

Dimiter Madjarov
Telerik team
 answered on 15 Apr 2015
1 answer
535 views

We are using dropdown inside a kendo grid. Inside the
dropdown we need to display a tree view. When user clicks dropdown, tree view should
be displayed. We have only two levels in the tree view. On selecting any item
or sub item from the treeview, text of the item should be shown as dropdown text and tree view
should get close. Inside a tree view we need page down/up.

If we put dropdown in the separate partial view outside the grid, then it is working.
But if we try to use dropdown inside the grid using editor template then tree view
is not working.

Following is the code snippet:

Index.cshtml
@(Html.Kendo().Grid<SampleModel>()
.Name("grdOutput").Scrollable(s => s.Height("auto"))
    .EnableCustomBinding(false)
    .Columns(columns =>
    {
        columns.Bound(o => o.Id).Title("Id");
        columns.Bound(s => s.Order).EditorTemplateName("_DropDownEditor").ClientTemplate("#=Order#").Title("Order");
        columns.Command(command => { command.Destroy(); }).Width("80px");
    })
     .ToolBar(toolbar => toolbar.Create())
     .Editable(editable => editable.Mode(GridEditMode.InCell))
    .Pageable(pageable => pageable
                                .Refresh(true)
                                    .PageSizes(new[] { 10, 15, 20 }))
    .Sortable()
    .Scrollable()
    .DataSource(dataSource => dataSource
        .Ajax()
                    .Model(model =>
                    {
                        model.Id(p => p.Id);
                        model.Field(p => p.Order).DefaultValue(
                           ViewData["defaultOrder"] as string);
                    })
                            .Read(read => read.Action("OutputRead", "Home"))
    )
        .Events(e =>
                {
                })
)
_DropDownEditor.cshtml
 
@using Kendo.Mvc.UI
@model string
@(Html.Kendo().DropDownList()
      .Name("Order")
          .BindTo(new[] {
                          new {
                              Text = "",
                              Value = ""
                          }})
      .DataTextField("Text")
      .DataValueField("Value")
      .Template(Html.Partial("EditorTemplates/_TreeViewEditor").ToHtmlString())
      .Events(e =>{ e.Open("OnOpen"); })
      )
TreeViewEditor.cshtml
<ul id="treeview">
    <li data-expanded="true">
        Item 1
        <ul>
            <li>Item 1.1</li>
            <li>Item 1.2</li>
        </ul>
    </li>
    <li data-expanded="true">
        Item 2
        <ul>
            <li>Item 2.1</li>
            <li>Item 2.2</li>
        </ul>
    </li>
    <li data-expanded="true">
        Item 2
        <ul>
            <li>Item 2.1</li>
            <li>Item 2.2</li>
        </ul>
    </li>
    <li data-expanded="true">
        Item 2
        <ul>
            <li>Item 2.1</li>
            <li>Item 2.2</li>
        </ul>
    </li>
    <li data-expanded="true">
        Item 2
        <ul>
            <li>Item 2.1</li>
            <li>Item 2.2</li>
        </ul>
    </li>
    <li data-expanded="true">
        Item 2
        <ul>
            <li>Item 2.1</li>
            <li>Item 2.2</li>
        </ul>
    </li>
</ul>
Common.js
function OnOpen(e) {
    setDropdownTreeView();
}
function setDropdownTreeView() {
    var treeview = $("#treeview").kendoTreeView({
        select: function (e) {
            // When a node is selected, display the text for the node in the dropdown and hide the treeview.
            $treeviewRootElem.slideToggle('fast', function () {
                $treeviewRootElem.removeClass("k-custom-visible");
            });
        }
    }).data("kendoTreeView");
    var $treeviewRootElem = $(treeview.element).closest("div.k-treeview");
 
    $(document).click(function (e) {
        // Ignore clicks on the treetriew.
        if ($(e.target).closest("div.k-treeview").length == 0) {
            // If visible, then close the treeview.
            if ($treeviewRootElem.hasClass("k-custom-visible")) {
                $treeviewRootElem.slideToggle('fast', function () {
                    $treeviewRootElem.removeClass("k-custom-visible");
                });
            }
        }
    });
}
SampleModel.cs
    public class SampleModel
    {
        public int Id { get; set; }
        public string Order { get; set; }
 
        public SampleModel()
        {
             
        }
        public SampleModel(int id,string o)
        {
            Id = id;
            Order = o;
        }
    }
}

 

Vladimir Iliev
Telerik team
 answered on 15 Apr 2015
3 answers
683 views
Hello,



We have a grid with two fields, each field has assigned a dropdownlist. The second dropdownlist has a behavior different, this dropdowonlist has enabled option
cascade and filtre with contains value. The question is, is it possible?

 

I show you the scenario:  


Code Grid

@(Html.Kendo().Grid<FareDetailViewModel>()
                            .Name("fare_details#=FareID#")
                            .ToolBar(t =>
                            {
                                if (User.IsInRole("Modify"))
                                {
                                    t.Create().Text("Afegir Referencia");
                                }
                            })
                            .Columns(columns =>
                            {
                                columns.ForeignKey(f => f.Tipus, (System.Collections.IEnumerable)ViewBag.CatalogTypes, "Key", "Value").EditorTemplateName("CustomGridForeignKeyFareType").Width(120);
                                //columns.ForeignKey(f => f.CatalogReference, (System.Collections.IEnumerable)ViewBag.Cataleg, "Reference", "Descripcio").EditorTemplateName("CatalegReferenceByType");
                                columns.Bound(f => f.CatalogReference).EditorTemplateName("CatalegReferenceByType").EditorViewData(new { gridid = "fare_details#=FareID#" });
Editor Template
@model object
 
@(Html.Kendo().DropDownList()
    .Name("CatalogReference" + ViewData["gridid"])
    .HtmlAttributes(new { data_bind = "value:CatalogReference" })
    .AutoBind(false)
    .OptionLabel("Select reference...")
    .DataTextField("Descripcio")
    .DataValueField("Reference")
    .Filter(FilterType.Contains)
    .MinLength(3)
    .ValuePrimitive(true)
    //.HtmlAttributes(new { data_skip = "true", data_bind = "defferedValue: object" })
    //.BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
    .DataSource(source =>
    {
        source.Read(read => read.Action("PopulateReferences", "Catalog").Data("filterTypes"))
            .ServerFiltering(true);
    })
    .CascadeFrom("Tipus")
    .HtmlAttributes(new { id = Guid.NewGuid().ToString() })
)
Function filterTypes
function filterTypes() {
            return {
                text: $("#Type").data("kendoDropDownList").value() + "|" + $("#CatalogReference" + temporalFare).data("kendoDropDownList").filterInput.val()
            };
        

Clarification: 

1) temporalFare the value maybe be for example fare_details26

2) $("#CatalogReference" + temporalFare).data("kendoDropDownList").filterInput.val() ===> Presents an error: Undefined.Action on controller



public JsonResult PopulateReferences(string text)
        {
            var param = text.Split('|');
            var type = (int)text[0];
            var search = text[1];
 
            var catalog = GetCatalog((catalogType)type).Where(c => (c.Descripcio + " " + c.Reference).Contains(search)).Select(c => new { Reference = c.Reference, Descripcio = c.Descripcio + " - " + c.Reference }).AsQueryable();
 
            return Json(catalog, JsonRequestBehavior.AllowGet);
        }


I hope that we can
clarify on this topic

 

 

Thanks in advance.

 

 

Xavier.

Xavier
Top achievements
Rank 1
 answered on 14 Apr 2015
2 answers
81 views

Hello,

I upgraded today to the MVC wrappers 2015.1.408 (I came from just the previous version, so really not far off).

But I encountered a breaking change I think.

I am using this dropdownlist:

@(Html.Kendo().DropDownList()
                  .Name("ddlExercise")
                  .DataTextField("Description")
                  .DataValueField("Id")
                  .OptionLabel("(Kies een oefening)")
                  .DataSource(source =>
                  {
                      source.Read(read =>
                      {
                          read.Action("GetExercises", "Exercise")
                              .Data("filterExercises");
                      })
                          .ServerFiltering(true);
                  })
                  .Events(events =>
                  {
                      events.Select("ddlExercise_select");
                      events.DataBound("ddlExercise_databound");
                  })
                  .HtmlAttributes(new { style = "width:300px" })
                  .Enable(false)
                  .AutoBind(false)
                  .CascadeFrom("ddlCourseLessonGroup")
                )

 

and in the ddlExercise_select event, I had this:

function ddlExercise_select(e) {
            var dataItem = this.dataItem(e.item.index());

            exerciseType = dataItem.Type;
            exerciseId = dataItem.Id;

            getExerciseDetailsAndInitialize();

        }

 

However, this now raised an issue that the first item in the dropdown list (apart from the optionlabel) would never have the "dataItem" variable defined. Other elements worked without a problem, but the first one did not. If I removed the optionlabel, it worked too.

In the end, what was able to solve this was to assign the dataitem as var dataItem = this.dataItem(e.item);

So basically dropping the ".index()".

Could you please confirm this is indeed a breaking change in 2015.1.408 and that dropping the ".index()" is the correct way to resolve this ?

Thank you

Georgi Krustev
Telerik team
 answered on 14 Apr 2015
2 answers
195 views

Hi

   i have 3 grid in my page - can i set theme for each one of them?

 

like:

grid1: theme default

grid2: theme Moonlight

grid3: theme bootstrap 

Ahmed
Top achievements
Rank 2
 answered on 14 Apr 2015
1 answer
364 views

I dont know if this is a bug or something something I could not find the documentation.

 

If you are using the EditorFor() and you supply a .Name() method in your form. On submit it will return a null value in MVC. I don't know why, it just does.

My hopes is that a moderator/dev can expand on this a little more and make add some more documentation/examples to the demos on the EditorFor component. 

Hopefully this helps someone. :)

So once I removed the ".Name("tkCommentEditor") line below from my code, it worked like I expected it to.

 

@(Html.Kendo().EditorFor(t => t.Body)
            .Name("tkCommentEditor")
            .Resizable()
            .Tools(tools => tools
            .Clear()
            .Formatting()
            .CleanFormatting()
            .FontName()
            .FontSize()
            .FontColor()
            .Bold().Italic().Underline().Strikethrough()
            .JustifyLeft().JustifyCenter().JustifyRight().JustifyFull()
            .Outdent().Indent()
            .SubScript().SuperScript()
            .TableEditing()
            .ViewHtml()
              )
        )

Alexander Popov
Telerik team
 answered on 14 Apr 2015
1 answer
101 views

Hello, 

I have datepicker in my view as below, But after adding event as http://demos.telerik.com/aspnet-mvc/datepicker/events, it lost its style and looks like Jquery UI datepicker. 

When i  looked at the source code, without using events, the input type is string and output is like below:

<span class="k-picker-wrap k-state-default"><input data-val="true" data-val-date="The field Hakediş T. must be a date." data-val-required="The Hakediş T. field is required." id="CmsProgressPaymentDate" name="CmsProgressPaymentDate" style="width: 100%;" type="text" value="13.04.2015" data-role="datepicker" class="k-input k-valid" role="combobox" aria-expanded="false" aria-owns="CmsProgressPaymentDate_dateview" aria-disabled="false" aria-readonly="false"><span unselectable="on" class="k-select" role="button" aria-controls="CmsProgressPaymentDate_dateview"><span unselectable="on" class="k-icon k-i-calendar">select</span></span></span>

But when i added the onchange or another events, the input type becomes to date and the output as below, 

<input data-val="true" data-val-date="The field Hakediş T. must be a date." data-val-required="The Hakediş T. field is required." id="CmsProgressPaymentDate" name="CmsProgressPaymentDate" style="width:100%" type="date" value="13.04.2015">

 

@(Html.Kendo().DatePickerFor(p=>p.CmsProgressPaymentDate)
            .Name("CmsProgressPaymentDate")
            .Value(System.DateTime.Now)
            .HtmlAttributes(new { style = "width:100%" })
}

Umut
Top achievements
Rank 1
 answered on 13 Apr 2015
Narrow your results
Selected tags
Tags
Grid
General Discussions
Scheduler
DropDownList
Chart
Editor
TreeView
DatePicker
Upload
ComboBox
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
ListView (Mobile)
Pager
Accessibility
ColorPicker
DateRangePicker
Wizard
Security
Styling
Chat
MediaPlayer
TileLayout
DateInput
Drawer
SplitView
Barcode
ButtonGroup (Mobile)
Drawer (Mobile)
ImageEditor
RadioGroup
Sparkline
Stepper
TabStrip (Mobile)
GridLayout
Template
Badge
LinearGauge
ModalView
ResponsivePanel
TextArea
Breadcrumb
ExpansionPanel
Rating
ScrollView
ButtonGroup
CheckBoxGroup
NavBar
ProgressBar
QRCode
RadioButton
Scroller
Timeline
TreeMap
TaskBoard
OrgChart
Captcha
ActionSheet
Signature
DateTimePicker
AppBar
BottomNavigation
Card
FloatingActionButton
Licensing
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
Ambisoft
Top achievements
Rank 2
Iron
Pascal
Top achievements
Rank 2
Iron
Matthew
Top achievements
Rank 1
Sergii
Top achievements
Rank 1
Iron
Iron
Andrey
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Ambisoft
Top achievements
Rank 2
Iron
Pascal
Top achievements
Rank 2
Iron
Matthew
Top achievements
Rank 1
Sergii
Top achievements
Rank 1
Iron
Iron
Andrey
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?