Telerik Forums
UI for ASP.NET MVC Forum
1 answer
1.1K+ views
Hi guys,

It’s possible to make a control dropdownlist with settings cascade enabled and filtered by contains too. I show you the scenario:


Grid code

@(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() {
            return {
                text: $("#Type").data("kendoDropDownList").value() + "|" + $("#CatalogReference" + temporalFare).data("kendoDropDownList").filterInput.val()
            };
        }


$("#CatalogReference" + temporalFare).data("kendoDropDownList") 
Here, I find the error.  Browser say me this expression is undefined

Controller Code

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 this is helpful code.

 

 

Thanks in advance.



Xavier.




Alexander Popov
Telerik team
 answered on 06 Apr 2015
2 answers
218 views
Hello,

I have used Kendo with MVC projects, and quite like it. 

Part of my evaluation is how easy it would be to retrofit a couple grids into legacy code-behind projects. 

Can I use the .Net helpers? Or do I have to use the pure HTML/Javascript methods? 

Being an MVC guy, I have not sent JSON to/from on a code-behind project before... In MVC the JSON is automatically converted into your viewmodel type onthe backend, if you C# class aligns with the JSON data. Is the same possible with CodeBehind?

Is there a simple example of a kendo grid using .net code-behind?

Thanks,

~S
Michael
Top achievements
Rank 1
 answered on 05 Apr 2015
1 answer
253 views


The following dropdownlist will not ever select any item except for the first (index 0):

  var clientList = HtmlExtensionMethods.GetClients().Select(c => new SelectListItem { Text = c.Value, Value = c.Key }).ToList();

 @(Html.Kendo().DropDownListFor(model => model.ClientID)
    .Name("ClientID")
    .BindTo(clientList)
    .DataTextField("Text")
    .DataValueField("Value")
    .Value(Model.ClientID)
    .Text(Model.ClientName)
    .HtmlAttributes(new { @class = "select wfull" })
  )

I have tried removing the Value and Text methods and adding .SelectedIndex(2) which does not work either.  The model.ClientID is a value in the selectlistitem.  How in the world can I get this dropdown to select the item with the value from model.  Nothing seems to work.

 v2014.3.1314



Boyan Dimitrov
Telerik team
 answered on 03 Apr 2015
1 answer
901 views
I am having difficulties in wiring up a custom EditorTemplate to a grid within an MVC 5 application. I have an integer field that only accepts a 1 or 2 as a value. Rather than using a standard numeric text box or slider control, I'd like to wire this up using buttons (via Bootstrap's group buttons). If the user clicks on the first button, the value should be set to 1, otherwise it should be set to 2.

The problem that I'm experiencing is that when the user clicks on the "edit" button, the "Level" value never gets applied to the editor template. The template displays as I'd like, but I cannot figure out how to bind the selected value back to the kendo grid. When the user clicks on the "save" button on the grid, the controller action is never invoked.

If I replace the editor template with a standard Kendo control such as a numeric text box or Kendo slider, it works fine.

ViewModel
public class LotViewModel
{
 
public int LotId { get; set; }
  [Display(Name = "Level")]
 
[Range(1, 2)]
 
[UIHint("LotLevel")]
 
public int Level { get; set; }
}
 
View
@(Html.Kendo().Grid<LotViewModel>()
  .Name("lotGrid")
  .Columns(columns =>
  {
    columns.Bound(x => x.LotId).Visible(false);
    columns.Bound(x => x.Level);
    columns.Command(command =>
    {
      command.Edit();
    }).Width(100);
  })
  .ToolBar(toolbar => toolbar.Create())
  .Editable(editable => editable.Mode(GridEditMode.InLine))
  .AutoBind(true)
  .DataSource(dataSource => dataSource
    .Ajax()
    .Model(model =>
    {
      model.Id(m => m.LotId);
      model.Field(m => m.Level).DefaultValue(1);
    })
    .Read(update => update.Action("GetLots", "Lot"))
    .Create(update => update.Action("CreateLot", "Lot"))
    .Update(update => update.Action("UpdateLot", "Lot"))
  )
  )


EditorTemplate: LotLevel
@model int
 
@{;
   var levelOne = Model.Equals(1) ? "active btn-primary" : null;
   var levelTwo = Model.Equals(2) ? "active btn-primary" : null;
  
  var htmlField = ViewData.TemplateInfo.HtmlFieldPrefix;
 }
 
@Html.HiddenFor(model => model)
  
<div class="btn-group btn-group-@htmlField">
  <button type="button"
          class="btn btn-default @levelOne bool-@htmlField"
          onclick="javascript: setValue(this, 1);">
    Level 1
  </button>
  <button type="button"
          class="btn btn-default @levelTwo bool-@htmlField"
          onclick="javascript:setValue(this, 2);">
    Level 2
  </button>
</div>
 
<script>
  function setValue(button, level) {
    $('.btn-group-@htmlField button.active').removeClass('active btn-primary');
    $(button).addClass('active btn-primary');
    $('#@htmlField').val(level); // TODO: Set the value of the model here
  }
</script>

Georgi Krustev
Telerik team
 answered on 03 Apr 2015
1 answer
335 views
I have a problem with the initial display of values in datepicker controls :

For example, April 3rd 2015 displays as 03/04/2015, but when opening the datepicker calendar, it has selected March 4th 2015 as date. Manually selecting April 3rd 2015 in the calendar again results in exactly the same display text (03/04/2015)...


Given a model which looks like this: 
[Display(Name = "Start Date")]
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
 

Configuration in web.config :
<system.web>
    <globalization uiCulture="en-GB" culture="en-GB"/>


Content in _Layout.cshtml
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="~/Content/Images/favicon.ico" type="image/x-icon" />
    <meta name="accept-language" content="en-GB" />

     @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/kendo/kendoscripts")
 
    @RenderSection("scripts", false)
    @RenderSection("scripts2", false)
 
    @Scripts.Render("~/bundles/Scripts/cultures/en")
    @Html.Kendo().DeferredScripts()
 
    <script type="text/javascript">
        var baseLocation = '@(Url.Content("~").TrimEnd('/'))';
        $(document).ready(function () {
            var data = $("meta[name='accept-language']").attr("content");
            kendo.culture(data);
        });
    </script>


BundleConfig :
bundles.Add(new ScriptBundle("~/bundles/Scripts/cultures/en")
              .Include("~/Scripts/kendo/cultures/kendo.culture.en-GB.min.js")
              .Include("~/Scripts/cultures/kendo.en-GB.js"));

Editor template :
@model DateTime?
 @(Html.Kendo().DatePickerFor(m => m).Deferred().HtmlAttributes(new { @class = "form-control k-datepicker-label-top" }))

cshtml page concerned:
<div class=" col-md-3">
    <div class="form-group">
@Html.LabelFor(m => m.StartDate)
@Html.EditorFor(m => m.StartDate)
   </div>
</div>

What am I missing here? 

Eric Kuijpers
Top achievements
Rank 1
 answered on 03 Apr 2015
4 answers
352 views
In your sample: http://www.kendoui.com/code-library/mvc/grid/custom-popup-editor.aspx

When I want to save I get an error that the field birthdate must be a date.

I even set DataType.Date annotation on that model property. But still I get this error.

How can I fix your broken sample?
Petur Subev
Telerik team
 answered on 02 Apr 2015
3 answers
194 views
To reproduce an issue a user recently posted related to Kendo grid, I thought it might be possible for me to use .NET Fiddle for it. But I am not able to load Kendo references. In my application I add a reference to Kendo.Mvc.dll.I am wondering is there a way I can add a reference in .NET fiddle. .NET fiddle supports Nuget package however Kendo MVC wrapper does not come in a package.

My fiddle is: https://dotnetfiddle.net/vRAJfO

Found that Kendo has got a tutorial that let you create charts and play around with it:http://dojo.telerik.com/. But it does not allow you to write ASP.NET MVC style code like .NET Fiddle does.

Is there a way we can create a fiddle using Kendo ASP.NET MVC wrapper?
Dimo
Telerik team
 answered on 02 Apr 2015
2 answers
378 views
I am using kendo grid with detail template, when the detail template binds to the existing grid row, everything works fine. Now I try to use javascript to add dynamic data and bind to the template, I receive javascript error "Email is not defined". It looks like the template's context is set to the current grid, how can i change it to bind to dynamic data, below is my code

@(Html.Kendo().Grid(Model.Customers)
    .Name("GridCustomers")
    .Columns(columns =>
    {
        columns.Bound(p => p.ID).Title("ID");
        columns.Bound(p => p.Name).Title("Name");
        columns.Bound(p => p.Telephone).Title("Telephone");
        columns.Bound(p => p.Extension).Title("Extension");
        columns.Bound(p => p.Group).Title("Group");

    })
    .HtmlAttributes(new { style = "height: 430px;" })
    .Pageable(pageable => pageable.Refresh(true).PageSizes(true).ButtonCount(5))
    .Sortable()
    .Scrollable()
    .ClientDetailTemplateId("template1")
    .DataSource(dataSource => dataSource
        .Ajax()
        .ServerOperation(false)
    )
    .Events(events => events.DetailExpand("onDetailExpand"))

)

<script id="template1" type="text/html">
    <div class='employee-details'>
        Contact Details:
        <ul>
            <li><label>Name:</label>#= Name #</li>
            <li><label>Mobile:</label>#= Telephone #</li>
            <li><label>E-mail Address:</label>#= Email #</li>
        </ul>
    </div>
</script>

<script>
    function dataBound() {
        this.expandRow(this.tbody.find("tr.k-master-row").first());
    }
    function onDetailExpand() {
        var javascriptTemplate = kendo.template($("#template1").html());
        var javascriptData = {FirstName: "Ziming", Telephone: "12345678", Email: "abc@abc.com"};
        $(".employee-details").html(javascriptTemplate(javascriptData));
    }
</script>
Ziming
Top achievements
Rank 1
 answered on 01 Apr 2015
1 answer
822 views
Hi,

I have Kendo MVC editable Grid  with Custom EditorTemplate for Numeric Text Box. For some reason I am getting validation error icon when i  try to update the value in numeric text box as in attached file.

I am not sure what kind of validation it is triggering as I have only required field validation. Can you pelase help me ASAP on this.


My model is as below

[Serializable]
    public class DocTypesModel
    {
        [Required(ErrorMessage = "required")]
        [UIHint("NumericTextBoxWithLimitsTemplate")]
        public int Order { get; set; }

        public int TotalCount { get; set; }

        public string DocumentTypeShortName { get; set; }      

    }

My grid is as below


 @(Html.Kendo().Grid(Model.DocTypesModel)
                      .Name("BookmarkDoctypeGrid")
                   
                     .Columns(columns =>
                      {
                            columns.Bound(c => c.Order).Sortable(false).EditorTemplateName("NumericTextBoxWithLimitsTemplate");
                          columns.Bound(c => c.DocumentTypeShortName).Title("Document Type").Sortable(false);
                        
                      })
                      .Editable(e => e.Mode(GridEditMode.InCell))
                      .Sortable()
                      .Events(e => e.DataBound("OnGridDocTypeDataBound").SaveChanges("SaveDocTypeChanges"))
                      .Resizable(resiz => resiz.Columns(false))
                      .DataSource( dataSource =>
                          dataSource.Ajax()
                           .AutoSync(true)
                           .ServerOperation(false)
                          .Update("Editing_Update", "Bookmark")
                              .Events(events => events.Error("error_handler"))
                        
                      )
                      )

I have created below custom editor for  NumericTextBoxWithLimitsTemplate under /views/shared/EditorTemplates/NumericTextBoxWithLimitsTemplate.cshtml

@model int

@(Html.Kendo()
.NumericTextBox().Step(1)
    .Name("Order").Decimals(0)
    .HtmlAttributes(new { Style = "width:70px;", required="required"})
         .Min(1).Max(short.MaxValue)
         
      

Thanks,
AArti



Boyan Dimitrov
Telerik team
 answered on 01 Apr 2015
4 answers
445 views
Hi Telerik.

I am trying to accomplish a scheduler with horizontal grouping of several resources, say mechanics.
So, I have a day view scheduler with a variable number of mechanics as resources on top, comparable to selecting the day view in this demo. Now, I have included the following code:
@(Html.Kendo().Scheduler<VisitViewModel>()
    .Name("scheduler")
    .Date(DateTime.Now)
    .StartTime(7, 0, 0)
    .EndTime(18, 0, 0)
    .Timezone("Etc/UTC")
    .AllDaySlot(false)
    .Views(views => {
        views.DayView(view => view.Selected(true)
            .WorkDayStart(8, 0, 0)
            .WorkDayEnd(17, 0, 0)
            .SelectedDateFormat("{0:dddd d/M/yyyy}"));
    })

.Resources(resource => resource
        .Add(m => m.MechanicId)
        .Title("Mechanic")
        .Name("mechanic")
        .Multiple(false)
        .DataTextField("Text")
        .DataValueField("Value")
        .BindTo(GetMechanics().Select(v => new { Text = String.Format("{0} {1}", v.FirstName, v.LastName), Value = v.Id }).ToArray()))

However, using the above code all mechanics obviously have exactly the same working hours, that is, from 8:00 to 17:00.
Imagine that I have two mechanics, say A and B, and that mechanic A usually works from 8:00 to 17:00 and mechanic B from 9:00 to 18:00.

How can I easily achieve this as the number of mechanics is variable and a mechanic's working hours is extracted from the database for a specific date?
What I would like to accomplish is to add the css class k-nonwork-hour to a resource's (mechanic) unavailable hours. I have an idea of how to obtain the desired result with javascript, but this approach is quite extensive and its code is complex to write and maintain. I wonder whether there's an easier way to achieve this.

I have already resolved this server-side so that you cannot drag and drop an event into a mechanic's unavailable hours, but I would like to show this unavailability visually in the scheduler itself as well.

I am looking forward to hearing from you soon. Thanks in advance!

Kind regards,
Mor
Mor
Top achievements
Rank 1
 answered on 01 Apr 2015
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?