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

I have implemented some server-side validation to prevent overlaps from occurring, but if an event fails twice in a row, it disappears entirely from the scheduler.

My scheduler is as follows:

@(Html.Kendo().Scheduler<MyEventViewModel>()
            .Name("Scheduler")
            .Date(DateTime.Today)
            .StartTime(DateTime.Today.AddHours(8))
            .Height(500)
            .Views(v => {
                v.DayView();
                v.WeekView();
                v.CustomView("TwoWeekView");
            })
            .Group(g =>
            {
                g.Resources("Labour");
                g.Date(true);
            })
            .Resources(resources => resources
                .Add(m=>m.LabourId)
                .Name("Labour")
                .Title("Labour")
                .DataValueField("Id")
                .DataTextField("FullName")
                .DataSource(dataSource => dataSource
                    .Read(read => read
                        .Action("LabourResourcesList", "Scheduler")
                        .Type(HttpVerbs.Post)
                        .Data("LabourResourceSelection")
                    )
                    .Events(e=>e.Change("RefreshSchedulerView"))
                )
            )
            .DataSource(dataSource => dataSource
                .Read(read => read
                    .Action("ScheduledEvents", "Scheduler")
                    .Type(HttpVerbs.Post)
                    .Data("LabourResourceSelection")
                )
                .Update("UpdateSchedule","Scheduler")
                .Model(m =>
                {
                    m.Field(f => f.Id);
                    m.Field(f => f.LabourId);
                    m.Field(f => f.Start);
                    m.Field(f => f.End);
                    m.Field(f => f.Description);
                    m.Field(f => f.JobCode);
                    m.Field(f => f.Title);
                })
                .Custom()
                .Type("aspnetmvc-ajax")
                .Schema(schema =>
                    schema.Model(model =>
                    {
                        model.Id(f => f.Id);
                        model.Field(f => f.LabourId);
                        model.Field("title", typeof(string)).From("Description");
                        model.Field("start", typeof(DateTime)).From("Start");
                        model.Field("end", typeof(DateTime)).From("End");
                        model.Field("description", typeof(string)).From("Description");
                        model.Field("LabourId", typeof(int)).From("LabourId");
                    })
                )
                .Events(e => e.RequestEnd("ValidationChecker"))
            )
            .AllDaySlot(false)
            .AutoBind(false)
        )

So as you can see I am grouping by "Labour",and each event has a corresponding "LabourId".

Updates are sent to the UpdateSchedule action in the SchedulerController, and I have added some server-side validation there to prevent each Labour resource having overlapping events. If all is well I return a null, and the scheduler does what it wants, if there is an overlap I return a JSON with some data to explain that the change is not possible. In the scheduler datasource you can see on the RequestEnd event I call a function "ValidationChecker", which checks the response data, and when the UpdateSchedule action indicates the change cannot be made, I do the following:

var scheduler = $("#Scheduler").data("kendoScheduler");
        scheduler.dataSource.cancelChanges();
        e.preventDefault();

This works, but it only works once consecutively. If I overlap two events, the change is rejected by the validation, and the event that was moved is snapped back to its original place. I can move it around some more and try again, and it will fail again. If two updates fail in a row, the event disappears entirely. I am not sure what is happening here.

Is there a correct way to cancel an update?

...also is there a way to specify a title for a custom view in the MVC scheduler?

Plamen
Telerik team
 answered on 14 Sep 2017
2 answers
363 views

Dear Telerik-team,

in my application, I am using the Kendo Map widget and bind it to a view model. Therefore, I followed this example:

http://docs.telerik.com/aspnet-mvc/helpers/map/how-to/bind-map-to-model

Works, the data coming from the database is displayed on the map as markers. That is the HTML code:

 

 @(Html.Kendo().Map()
                .Name(Model.Name)
                .Center(Model.CenterLatitude, Model.CenterLongitude)
                .Zoom(Model.Zoom)                
                .Layers(layers => layers
                    .Add()
                    .Type(MapLayerType.Tile)
                    .UrlTemplate(Model.TileUrlTemplate)
                    .Subdomains(Model.TileSubdomains)
                    .Attribution(Model.TileAttribution)
                )
                .Markers(markers =>
                {
                    foreach (var marker in Model.Markers)
                    {
                        markers.Add()                        
                        .Location(marker.latlng)
                        .Title(marker.name);
                    }
                })
                .Events(events => events
                    .MarkerClick("onMarkerClick"))
            )

I want to redirect to a controller action when a user clicks on a marker. Ideally by passing an ID to that controller action in order to fetch the corresponding data of the item from the database. Is there a way to attach the ID of the item, the markers represent, to the marker (like it is possible to specify a title e.g.)?

And how would in this case look the javascript method whichs would call the controller action? 

I tried to display the name of the marker with the following javascript:

<script>

    function onMarkerClick(e) {
        var dataItem = e.sender.marker.dataItem;
        alert(dataItem.name)        
    }
</script>

But this doesn't work :-/

Happy to hear from you,

best regards,

Marco

Marco Beyer
Top achievements
Rank 1
 answered on 13 Sep 2017
1 answer
143 views

Kendo UI for jQuery documentation at http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#configuration-columns.selectable states

"As of the Kendo UI R2 2017 SP1 release, the selection of columns with checkboxes is a built-in feature for the Grid..."

There does not seem to be a HtmHelper in Razor in Telerik UI for ASP.NET MVC for adding the selectable 'column' of checkboxes as in the manner shown for Kendo UI sample at https://dojo.telerik.com/ehaDo

In this sample, a SQL pivot view is surfaced to the page as a Grid<dynamic> because the pivot columns are unknown at coding time.  The DataTable of the pivot view is delivered via ViewBag so the Model can be built and fields added dynamically to the grid at init time.

There is no 'columns.Selectable()' as I might expect.

@(Html.Kendo().Grid<dynamic>()
   .Name("master")
   .DataSource(dataSource => dataSource
       .Ajax()
       .Model(model =>
       {
           var id = ViewBag.TestGridDataTable.PrimaryKey[0].ColumnName;
           model.Id(id);
           foreach (System.Data.DataColumn column in ViewBag.TestGridDataTable.Columns)
           {
               model.Field(column.ColumnName, column.DataType).Editable(false)
               ;
           }
       })
       .Read(read => read.Action("Read", "Results"))
   )
   .Columns(columns =>
   {
       columns.Selectable();  // <----- does not add a check box column
 
       foreach (System.Data.DataColumn column in ViewBag.TestGridDataTable.Columns)
       {
           columns.Bound(cn);
       }
   })

Do I have to create a new version of the model with an extra boolean field and go from there ?

Angel Petrov
Telerik team
 answered on 13 Sep 2017
10 answers
925 views

I just updated to release '2015.1.318' and a Grid that was working fine with several ForeignKey columns bound to Guid and selectlists is now not working. I add and update In-Line on the grid. Now when I CREATE a new Entity inline - the editor displays all the data perfectly but the data sent to the server does not include the values selected for the ForeignKey columns. These are sent as Empty Guids i.e.00000000-0000-0000-0000-000000000000.

Note - when I UPDATE an existing entity it all works fine, the problem is only when I CREATE\INSERT.

The code for the Grid is below and the EditorTemplate for the ForeignKey column is also there.

 

Grid

<script type="text/javascript">
  function gridEntityAssignments_CreateData() {
      return {
        assignedTo: "@(assignedTo)",
        assignedToOid: "@(assignedToOid)",
      };
  }
</script>
@*All Required*@
@Html.Hidden("IsAssignments", isAssignments)
@Html.Hidden("AssignmentsAssignedToOid", assignedToOid)
@Html.Hidden("AssignmentsAssignedTo", assignedTo)
 
<div style="width: 100%">
  @(Html.Kendo().Grid<Mallon.AssignedTo.Models.ViewGridAssignment>()
  .Name("GridEntityAssignments")
  .AutoBind(isAssignments) //if false - Report not loaded on page initialise
  .HtmlAttributes(new { @class = "ignore" })
  .ToolBar(toolbar =>
  {
    toolbar.Create().HtmlAttributes(new { @class = "dfw-ignoreDirtyLink" });
  })
  .Editable(editable => editable.Mode(GridEditMode.InLine))
  .Scrollable(s => s.Height("auto"))
  .Columns(columns =>
  {
    columns.Bound(p => p.Oid).Visible(false);
    columns.ForeignKey(p => p.UserOid, (System.Collections.IEnumerable)ViewData["AssignmentUsers"], "Value", "Text").EditorTemplateName("GridForeignKeyWithSelect").Title("User");
    columns.ForeignKey(p => p.AssignmentTypeOid, (System.Collections.IEnumerable)ViewData["AssignmentTypes"], "Value", "Text").EditorTemplateName("GridForeignKeyWithSelect").Title("Type");
    columns.Bound(p => p.Info).EditorTemplateName("GridTextArea");
    columns.Command(command => { command.Edit(); command.Destroy(); }).Width(172);
  })
  .DataSource(dataSource => dataSource
    .Ajax()
    .AutoSync(false)
    .Model(model =>
    {
      model.Id(p => p.Oid);
      model.Field(p => p.Oid).DefaultValue(Guid.Empty);
    })
    .Events(e => e.Error("handleAjaxError"))
    .Destroy(update => update.Action("Assignments_GridDelete", "Assignment"))
    .Update(update => update.Action("Assignments_GridUpdate", "Assignment"))
    .Create(update => update.Action("Assignments_GridCreate", "Assignment").Data("gridEntityAssignments_CreateData"))
    .Read(read => read.Action("Assignments_GridRead", "Assignment", new { assignedToOid = assignedToOid }))
  )
)
 
</div>

 

 Editor Template

 

@model object
 
@(
 Html.Kendo().DropDownListFor(m => m)
        .BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"]).OptionLabel("Please Select")
)

 

 

 

 

 

 

 

 

 

 

 

Konstantin Dikov
Telerik team
 answered on 13 Sep 2017
2 answers
909 views

When I add a new event programmatically:

var scheduler = $("#Scheduler").data("kendoScheduler");
scheduler.dataSource.add(newEvent);

In cases where I do not assign an ID to a new event, the Create method is called instantly upon adding the new event, which is great; no problems there.

When I do assign an ID, the Update event is not fired, which is a bit unexpected. If the new event is moved or resized then the appropriate event is fired, but I would like to immediately call the Update function with the newly added event.

I have tried:

scheduler.dataSource.sync()

...but this does not work; the Update method is not called.

If I dig in to the data itself, pick out the relevant event, and call the update function, for example:

scheduler.data()[1].update()

Still no luck, no update method is called. I'm stumped.

How do I trigger an Update for a newly added event?

#MagiCSS-bookmarklet,html>body #MagiCSS-bookmarklet{display: block;} #MagiCSS-bookmarklet .cancelDragHandle{cursor: default;}
Deactivated the code
Dimitar
Telerik team
 answered on 13 Sep 2017
3 answers
504 views

I used kendo window with my application and I notice that when I resize the browser to smaller size, kendo window overflows. I have set my kendo window size to 1200. How can I make my kendo window responsive?

 

Ivan Zhekov
Telerik team
 answered on 13 Sep 2017
1 answer
372 views

when I UPDATE an existing entity it all works fine, the problem is only when I CREATE\INSERT.

 

Here is the code below please help

 

        <div>
                @*Phone Carrier*@
                @(Html.Kendo().Grid<OSH.Domain.Models.PhoneCarrier.AppPhoneCarrierItem>()
                .Name("CarrierGrid")
                .Columns(columns =>
                {
                    columns.Bound(e => e.PhoneCarrierId).Width(350).Hidden();
                    columns.Bound(e => e.PhoneCarrier).Width(350);
                    columns.Command(command => { command.Edit().Text(" "); command.Destroy().Text(" "); });
                })
                .ToolBar(toolbar => { toolbar.Create().Text("Add New Carrier"); })
                .Editable(editable => editable.Mode(GridEditMode.InLine))
                .Sortable()
                .Pageable()
                .Scrollable()
                .ColumnMenu()
                .Filterable()
                .HtmlAttributes(new { style = "height:420px;" })
                .DataSource(dataSource => dataSource
                    .Ajax()
                    .PageSize(10)
                    .Model(model => model.Id(p => p.PhoneCarrierId))
                    .Read(read => read.Action("readCarrier", "Admin"))
                    .Create(update => update.Action("CreateCarrier", "Admin"))
                    .Update(update => update.Action("EditCarrier", "Admin"))
                    .Destroy(update => update.Action("DeleteCarrier", "Admin"))
                    .Events(events => events.Error("onError3").Sync("sync_handler"))
                    )
                .Pageable(x => x.PageSizes(new List<object> { 5, 10, 15, 20, "all" }).Refresh(true))
                .Resizable(resize => resize.Columns(true))
                .Reorderable(reorder => reorder.Columns(true))
                )
            </div>

 <div>
                @*Phone Number*@
                @(Html.Kendo().Grid<OSH.Domain.Models.PhoneNumber.AppPhoneNumberItem>()
                .Name("PhoneNumberGrid")
                .Columns(columns =>
                {
                    columns.Bound(e => e.PhoneNumber);
                    columns.Bound(e => e.Description);
                    //columns.Bound(e => e.PhoneNumberTypeId);
                    //columns.Bound(e => e.PhoneCarrierId);
                    columns.ForeignKey(e => e.PhoneNumberTypeId, (System.Collections.IEnumerable)ViewData["PNType"], "PhoneNumberTypeId", "PhoneNumberType")
                   .Title("Phone Number Type");
                    columns.ForeignKey(e => e.PhoneCarrierId, (System.Collections.IEnumerable)ViewData["PhoneCarrier"], "PhoneCarrierId", "PhoneCarrier")
               .Title("Phone Carrier");
                    columns.ForeignKey(e => e.LocationId, (System.Collections.IEnumerable)ViewData["Location"], "LocationId", "LocationName")
               .Title("Location");
                    //columns.Bound(e => e.LocationId);
                    columns.Command(command => { command.Edit().Text(" "); command.Destroy().Text(" "); });
                })
                .ToolBar(toolbar => { toolbar.Create(); })
                .Editable(editable => editable.Mode(GridEditMode.InLine))
                .Sortable()
                .Pageable()
                .Scrollable()
                .ColumnMenu()
                .Filterable()
                .HtmlAttributes(new { style = "height:420px;", data_value_primitive = "true" })
                .DataSource(dataSource => dataSource
                    .Ajax()
                    .PageSize(10)
                    .Model(model => model.Id(p => p.PhoneCarrierId))
                    .Read(read => read.Action("readPhoneNumber", "Admin"))
                    .Create(update => update.Action("CreatePhoneNumber", "Admin"))
                    .Update(update => update.Action("EditPhoneNumber", "Admin"))
                    .Destroy(update => update.Action("DeletePhoneNumber", "Admin"))
                    .Events(events => events.Error("error_handler").Sync("sync_handler"))
                    )
                .Pageable(x => x.PageSizes(new List<object> { 5, 10, 15, 20, "all" }).Refresh(true))
                .Events(e => e.Edit("onPhoneNumberGridEdit").Save("onSavingPhoneNumber"))
                .Resizable(resize => resize.Columns(true))
                .Reorderable(reorder => reorder.Columns(true))
                )
            </div>
        </div>

 

  function onSelect(e) {
                var x = e.item;
                var tabSelectedIndex = $(x).index();
                if (tabSelectedIndex == 2) {
                    $.ajax({
                        url: '@Url.Action("UpdateNewDataType", "Admin")',
                        cache: false,
                        type: 'GET',
                        success: function (Newdata) {
                            var data = [];
                            for (var i = 0; i < Newdata.length; i++) {
                                data.push({ text: Newdata[i].PhoneNumberType, value: Newdata[i].PhoneNumberTypeId });
                            }
                            var grid = $("#PhoneNumberGrid").data("kendoGrid");
                            grid.columns.filter(function (item) {
                                return item.field === "PhoneNumberTypeId";
                            }).forEach(function (item) {
                                item.values = data;
                            });
                            grid.setOptions({ columns: grid.columns, toolbar: [{ name: "create", text: "Add Phone Number" }] });
                            grid.refresh();
                        }
                    });


                    $.ajax({
                        url: '@Url.Action("UpdateNewDataCarrier", "Admin")',
                        cache: false,
                        type: 'GET',
                        success: function (Newdata) {
                            var data = [];
                            for (var i = 0; i < Newdata.length; i++) {
                                data.push({ text: Newdata[i].PhoneCarrier, value: Newdata[i].PhoneCarrierId });
                            }
                            var grid = $("#PhoneNumberGrid").data("kendoGrid");
                            grid.columns.filter(function (item) {
                                return item.field === "PhoneCarrierId";
                            }).forEach(function (item) {
                                item.values = data;
                            });
                            grid.setOptions({ columns: grid.columns, toolbar: [{ name: "create", text: "Add Phone Number" }] });
                            grid.refresh();
                        }
                    });
                }

            }

 

function onSavingPhoneNumber(e) {
            $("#PhoneNumberGrid tbody [data-role=dropdownlist]").each(function () {
                var ddl = $(this).data("kendoDropDownList");
                if (ddl) {
                    var v = ddl.value();
                    var p = ddl.list.attr('id').replace('-list', '');
                    if (p) e.model.set(p, v);
                }
            })

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

Controller

 

   public ActionResult EditPhoneNumber([DataSourceRequest] DataSourceRequest request, AppPhoneNumberItem AppPhoneNumberItem)
        {
            PhoneNumberUpdateResponse response = new PhoneNumberUpdateResponse();
            if (AppPhoneNumberItem != null && ModelState.IsValid)
            {
                PhoneNumberRequest request2 = new PhoneNumberRequest();
                request2.PhoneNumberId = AppPhoneNumberItem.PhoneNumberId;
                request2.PhoneNumber = AppPhoneNumberItem.PhoneNumber;
                request2.Description = AppPhoneNumberItem.Description;
                request2.PhoneNumberTypeId = AppPhoneNumberItem.PhoneNumberTypeId;
                request2.PhoneCarrierId = AppPhoneNumberItem.PhoneCarrierId;
                request2.LocationId = AppPhoneNumberItem.LocationId;
                response = phoneNumberApi.UpdatePhoneNumber(request2);
                if (response.Error != null)
                {
                    ErrorLogRequest errorReq = new ErrorLogRequest()
                    {
                        LogDate = DateTime.Now,
                        LogMethod = "UpdatePhoneNumber",
                        LogPage = "Admin",
                        LogPerson = User.Identity.Name,
                        LogInfo = response.Error.ErrorCode + " " + response.Error.ErrorMessage + " " + response.Error.ExceptionObject.Message
                    };
                    apiErrorLog.InsertErrorLog(errorReq);
                }
            }
            BindViewBag();
            return Json(new[] { response }.ToDataSourceResult(request, ModelState));
        }

 

public void BindViewBag()
        {

 ViewData["PhoneCarrier"] = PhoneCarrier;
            ContactTypeRequest request4 = new ContactTypeRequest();
            var ContactType = contactTypeApi.GetContactTypeList(request4).data.Select(p => new AppContactTypeItem()
            {
                ContactTypeId = p.ContactTypeItem.ContactTypeId,
                ContactType = p.ContactTypeItem.ContactType
            });

}

Stefan
Telerik team
 answered on 13 Sep 2017
1 answer
649 views
In this example, the filename is hardcoded.  Is it possible to dynamically change the filename? For example add current date/time.
Preslav
Telerik team
 answered on 12 Sep 2017
2 answers
376 views

I have added a view to my scheduler:

@(Html.Kendo().Scheduler<MyEventViewModel>()
                .Name("Scheduler")
                .Views(v => {
                    v.DayView();
                    v.WeekView();
                    v.CustomView("MyCustomView");
                })

...and so on

...and I have defined this custom view as follows:

var MyCustomView = kendo.ui.MultiDayView.extend({
    options: {
        selectedDateFormat: "{0:D} - {1:D}",

        title: "this does not work"

    },
     title: "this does not work, either",
    calculateDateRange: function () {
        var start = this.options.date,
            idx, length,
            dates = [];
        for (idx = 0, length = 14; idx < length; idx++) {
            dates.push(start);
            start = kendo.date.nextDay(start);
        }
        this._render(dates);
    }
})

But I cannot seem to provide a title to this view to appear on the button. Specifying a title either in the view config, or the options of the view config does not work, and the CustomView method takes only one argument. I believe the javascript equivalent takes two arguments, with one being the title of the custom view, but the MVC version does not. ...so where do I set the title?

Dimitar
Telerik team
 answered on 12 Sep 2017
1 answer
381 views

Hello,

I'm looking for add a target blank to an url but i wonder how to do it:

        @(Html.Kendo().TreeView()
        .Name("treeview-right")
        .DragAndDrop(true)
        .Items(treeview =>
        {

            treeview.Add().Text("Accès Mirakl")
                          .Url("http://google.com")
                          .ImageUrl(Url.Content("~/Content/images/internet_16x16.png"));

            treeview.Add().Text("Wiki Mirakl")
                          .Url("http://goole.fr")
                          .ImageUrl(Url.Content("~/Content/images/ampoule_16x16.png"));
        })

Neli
Telerik team
 answered on 12 Sep 2017
Narrow your results
Selected tags
Tags
+? more
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?