This is a migrated thread and some comments may be shown as answers.

Additional Field in Template doesn't set model

1 Answer 134 Views
Scheduler
This is a migrated thread and some comments may be shown as answers.
Lorenzo
Top achievements
Rank 1
Lorenzo asked on 15 Oct 2015, 08:55 AM

Hi there,

I want to add a ​TextField (or hidden) item into the form template. This Filed is Filled by jquery in this way: there is a button in the template that open a window (from partial view), this window, on close, set the value.

The form is working correctly, but the inventoryItems is not transferred in the server request for saving the event.
What am I missing?

 

My Model:

public class CalendarModel : BaseCalendarModel
{
    public int cae_ID { get; set; }
 
    public string cae_Timezone { get; set; }
    public int? cae_EventType { get; set; }
    public string inventoryItems { get; set; }
}

 

My Scheduler:

<link href="@Url.Content("~/Areas/Calendar/Content/toDoViewStyle.css?v=0.1")" rel="stylesheet" type="text/css" />
@{
    Layout = "~/Areas/Calendar/Views/Shared/_LayoutCalendar.cshtml";
}
 
<script src="@Url.Content("~/Areas/Calendar/Scripts/toDoView.js?v=0.1")"></script>
 
<div class="spacer"> </div>
 
@(Html.Kendo().Scheduler<Clingo5.Areas.Calendar.Models.CalendarModel>()
    .Name("scheduler")
    .Date(DateTime.Today)
    .StartTime(new DateTime(2015, 1, 1, 7, 0, 0))
    .Height(800)
    .Views(views =>
    {
        views.DayView();
        views.WorkWeekView();
        views.WeekView();
        views.MonthView(monthView => monthView.Selected(true));
        views.CustomView("CustomAgenda", view => view.Title("Agenda"));
        views.CustomView("kendo.ui.ToDoView", view => view.Title("To Do"));
    })
        .Editable(editable =>
        {
            editable.TemplateName("CustomEditorTemplate").Window(w => w
                .Name("Nuovo Appuntamento")
                .HtmlAttributes(new {id="newAppointment"})
                );
        })
    .Timezone("Etc/UTC")
    .WorkDayStart(9, 0, 0)
    .WorkDayEnd(18, 0, 0)
    .WorkWeekStart(1)
    .WorkWeekEnd(5)
    .Messages(messages =>
        {
            messages.Today("Oggi");
        }
    )
    .Resources(resource =>
        {
            resource.Add(m => m.cae_EventType)
                .Title("Tipo")
                .DataTextField("Text")
                .DataValueField("Value")
                .DataColorField("Color")
                .BindTo(new[] {
                new { Text = "Verifica Sicurezza", Value = 1, Color = "\\#6eb3fa" },
                new { Text = "Manutenzione Preventiva", Value = 2, Color = "\\#f58a8a" }
                });
        })
    .DataSource(d => d
    .Model(m =>
    {
        m.RecurrenceId(f => f.RecurrenceID);
        m.Id(f => f.cae_ID);
        m.Field(f => f.Title).DefaultValue("Nuovo Evento");
    })
        .Events(e => e.Error("error_handler"))
        .Read("GetAll", "Calendar")
        .Create("Calendar_Create", "Calendar")
        .Destroy("Calendar_Destroy", "Calendar")
        .Update("Calendar_Update", "Calendar")
    )
        //.BindTo(Model)
)
 
<script type="text/javascript">
    //Script per customizzare l'agenda
    var CustomAgenda = kendo.ui.AgendaView.extend({
        endDate: function () {
            var date = kendo.ui.AgendaView.fn.endDate.call(this);
            return kendo.date.addDays(date, 31);
        }
    });
 
    //Apertura griglia elementi
    function ClickButton(e) {
        e.preventDefault();
        var width = parseInt($("#dialogInventory").parent().parent().width() * 0.9);
        OpenDialog('grid', width, 768, 1);
    }
 
    function OpenDialog(formId, width, height, recordId) {
        $("#dialogInventory").width(width);
        $("#dialogInventory").data("kendoWindow").open().center(true);
    }
 
    //gestione check sulla griglia di selezione
    var checkedIds = {};
 
    function onDataBound(e) {
        var view = this.dataSource.view();
        for (var i = 0; i < view.length; i++) {
            if (checkedIds[view[i].id]) {
                this.tbody.find("tr[data-uid='" + view[i].uid + "']")
                    .addClass("k-state-selected")
                    .find(".checkbox")
                    .attr("checked", "checked");
            }
        }
 
        $(".checkbox").bind("change", function (e) {
            var row = $(e.target).closest("tr");
            row.toggleClass("k-state-selected");
            var checked = $(this).is(':checked');
            var grid = $('#grid').data().kendoGrid;
            var dataItem = grid.dataItem(row);
            checkedIds[dataItem.id] = checked;
        });
 
    }
 
 
    function VerifyChecked() {
        var checked = [];
        for (var i in checkedIds) {
            if (checkedIds[i]) {
                checked.push(i);
            }
        }
        //converto a stringa
        checked = checked + "";
        //alert(checked);
        $("#Inventory").val(checked);
        @*$.ajax({
                cache: false,
                type: "POST",
                url: "@(Url.Action("SetField", "Calendar"))",
            data: { "selectedItems": checked },
            error:function (xhr, ajaxOptions, thrownError){
                alert('Failed to return core and type field attributes.');
            }
        });*@
        $("#dialogInventory").data("kendoWindow").close();
    }
 
    function CloseInventoryWindow() {
        $("#dialogInventory").data("kendoWindow").close();
    }
 
    function checkAll(e) {
        var checked = $(e).is(':checked');
        var grid = $('#grid').data().kendoGrid;
        $.each(grid.dataSource.view(), function () {
            var id = this['id'];
            if (this['IsExpectedPreventiveMaintenance'] != checked)
                this.dirty = true;
            this['IsExpectedPreventiveMaintenance'] = checked;
            checkedIds[id] = checked;
        });
        grid.refresh();
    }
 
    //gestione errori calendario
    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);
 
            var scheduler = $("#scheduler").data("kendoScheduler");
            scheduler.one("dataBinding", function (e) {
                //prevent saving if server error is thrown
                e.preventDefault();
            })
        }
    }
</script>

My Template:

@model Clingo5.Areas.Calendar.Models.CalendarModel
 
@functions{
    public Dictionary<string, object> generateDatePickerAttributes(
             string elementId,
             string fieldName,
             string dataBindAttribute,
             Dictionary<string, object> additionalAttributes = null)
    {
 
        Dictionary<string, object> datePickerAttributes = additionalAttributes != null ? new Dictionary<string, object>(additionalAttributes) : new Dictionary<string, object>();
 
        datePickerAttributes["id"] = elementId;
        datePickerAttributes["name"] = fieldName;
        datePickerAttributes["data-bind"] = dataBindAttribute;
        datePickerAttributes["required"] = "required";
        datePickerAttributes["style"] = "z-index: inherit;";
 
        return datePickerAttributes;
    }
}
 
<div class="k-edit-label">
    @(Html.LabelFor(model => model.Title))
</div>
<div data-container-for="title" class="k-edit-field">
    @(Html.TextBoxFor(model => model.Title, new { @class = "k-textbox", data_bind = "value:title" }))
</div>
 
<div class="k-edit-label">
    @(Html.LabelFor(model => model.Start))
</div>
<div data-container-for="start" class="k-edit-field">
 
    @(Html.Kendo().DateTimePickerFor(model => model.Start)
          .HtmlAttributes(generateDatePickerAttributes("startDateTime", "start", "value:start,invisible:isAllDay")))
 
    @(Html.Kendo().DatePickerFor(model => model.Start)
          .HtmlAttributes(generateDatePickerAttributes("startDate", "start", "value:start,visible:isAllDay")))
 
    <span data-bind="text: startTimezone"></span>
    <span data-for="start" class="k-invalid-msg"></span>
</div>
 
<div class="k-edit-label">
    @(Html.LabelFor(model => model.End))
</div>
<div data-container-for="end" class="k-edit-field">
 
    @(Html.Kendo().DateTimePickerFor(model => model.End)
          .HtmlAttributes(generateDatePickerAttributes(
                "endDateTime",
                "end",
                "value:end,invisible:isAllDay",
                new Dictionary<string, object>() { { "data-dateCompare-msg", "End date should be greater than or equal to the start date" } })))
 
    @(Html.Kendo().DatePickerFor(model => model.End)
          .HtmlAttributes(generateDatePickerAttributes(
                "endDate",
                "end",
                "value:end,visible:isAllDay",
                new Dictionary<string, object>() { { "data-dateCompare-msg", "End date should be greater than or equal to the start date" } })))
 
    <span data-bind="text: endTimezone"></span>
    <span data-for="end" class="k-invalid-msg"></span>
</div>
 
<div class="k-edit-label">
    @(Html.LabelFor(model => model.IsAllDay))
</div>
<div data-container-for="isAllDay" class="k-edit-field">
    <input data-bind="checked: isAllDay" data-val="true" id="IsAllDay" name="IsAllDay" type="checkbox" />
</div>
 
<div class="endTimezoneRow">
    <div class="k-edit-label"></div>
    <div class="k-edit-field">
        <label class="k-check">
            <input checked="checked" class="k-timezone-toggle" type="checkbox" value="true" />
            Use separate start and end time zones
        </label>
    </div>
</div>
<script>
    $(".k-timezone-toggle").on("click", function () {
        var isVisible = $(this).is(":checked");
        var container = $(this).closest(".k-popup-edit-form");
 
        var endTimezoneRow = container.find("label[for='EndTimezone']").parent().add(container.find("div[data-container-for='endTimezone']"));
        endTimezoneRow.toggle(isVisible);
 
        if (!isVisible) {
            var uid = container.attr("data-uid");
            var scheduler = $("\#scheduler").data("kendoScheduler");
            var model = scheduler.dataSource.getByUid(uid);
            model.set("endTimezone", null);
        }
    });
 
    var endTimezone = '${data.endTimezone}';
 
    if (!endTimezone || endTimezone == "null") {
        $(".k-timezone-toggle").trigger('click');
    }
</script>
 
<div class="k-edit-label">
    @(Html.LabelFor(model => model.StartTimezone))
</div>
<div data-container-for="startTimezone" class="k-edit-field">
    @(Html.Kendo().TimezoneEditorFor(model => model.StartTimezone)
          .HtmlAttributes(new { data_bind = "value:startTimezone" }))
</div>
 
<div class="k-edit-label">
    @(Html.LabelFor(model => model.EndTimezone))
</div>
<div data-container-for="endTimezone" class="k-edit-field">
    @(Html.Kendo().TimezoneEditorFor(model => model.EndTimezone)
          .HtmlAttributes(new { data_bind = "value:endTimezone" }))
</div>
 
<div class="k-edit-label">
    @(Html.LabelFor(model => model.RecurrenceRule))
</div>
<div data-container-for="recurrenceRule" class="k-edit-field">
    @(Html.Kendo().RecurrenceEditorFor(model => model.RecurrenceRule)
          .HtmlAttributes(new { data_bind = "value:recurrenceRule" }))
</div>
 
<div class="k-edit-label">
    @(Html.LabelFor(model => model.Description))
</div>
<div data-container-for="description" class="k-edit-field">
    @(Html.TextAreaFor(model => model.Description, new { @class = "k-textbox", data_bind = "value:description" }))
</div>
 
<div class="k-edit-label">
    @(Html.LabelFor(model => model.cae_EventType))
</div>
<div data-container-for="cae_EventType" class="k-edit-field">
    @(Html.Kendo().DropDownListFor(model => model.cae_EventType)
          .HtmlAttributes(new { data_bind = "value:cae_EventType", style = "width: 200px" })
          .DataTextField("Text")
          .DataValueField("Value")
          .OptionLabel("None")
          .ValuePrimitive(true)
          .Template("<span class='k-scheduler-mark' style='background-color:\\#= data.Color?Color:'' \\#'></span>\\#=Text\\#")
          .BindTo(new[] {
                new { Text = "Verifica Sicurezza", Value = 1, Color = "\\#6eb3fa" },
                new { Text = "Manutenzione Preventiva", Value = 2, Color = "\\#f58a8a" }
            }).ToClientTemplate()
    )
</div>
 
 
<div data-container-for="inventoryItems" class="k-edit-field">
    @(Html.TextBoxFor(model => model.inventoryItems, new { @class = "k-textbox", data_bind = "value:inventoryItems" }))
</div>
<div class="k-edit-field">
    @(Html.Kendo().Button()
        .Name("openButton")
        .Content("Apri Inventario")
        .HtmlAttributes(new { type = "button" })
        .Events(ev => ev.Click("ClickButton"))
    )
</div>
 
 
<div>
    @(Html.Kendo().Window()
             .Name("dialogInventory")
             .Title("Search Items")
             .LoadContentFrom("PartialGrid", "Calendar")
             .Draggable()
             .Actions(actions => actions
                 .Close()
                )
             .Modal(true).Visible(false)
             .Resizable()
             .Height(800)
             //.Width(1200)
             .Position(pos => pos.Top(50))
    )
</div>

My Partial:

@model System.Data.DataTable
@{
    IEnumerable<string> pages;
    var pagesList = new List<string> { "All", "10", "20", "50", "100" };
    pages = pagesList;
}
 
@{
    var culture = Clingo5.MvcApplication.LoggedUser.CultureInfo;
}
<script src="@Url.Content("~/Content/plugin/kendo/cultures/kendo.culture." + culture + ".min.js")"></script>
<script>
        @if (Clingo5.MvcApplication.LoggedUser != null && !string.IsNullOrEmpty(Clingo5.MvcApplication.LoggedUser.ShortCulture))
        {
       <text>
    $("html").prop("lang", "@(Clingo5.MvcApplication.LoggedUser.ShortCulture)");
    </text>
                      }
</script>
 
<script type="text/javascript">
    //set the Kendo UI culture
    $(function () {
        kendo.culture("@culture");
    })
</script>
 
<div id="search_grid">
    @(Html.Kendo().Grid<dynamic>()
     .Name("grid")
            //.Selectable(s => s.Mode(GridSelectionMode.Multiple))
     .Columns(columns =>
     {
         List<string> columnElaborated = new List<string>();
         //ciclo iniziale
         foreach (System.Data.DataColumn column in Model.Columns)
         {
             //controllo che non sia stato già inserita la colonna in un raggruppamento
             if (!columnElaborated.Contains(column.ColumnName))
             {
                 //verifico che la colonna sia da raggruppare
                 if (column.ColumnName.ToString().IndexOf("_") > 0)
                 {
                     char[] delimiterChars = { '_' };
                     string[] title = column.ColumnName.ToString().Split(delimiterChars);
                     if (title[0].Length > 0)
                     {
                         //raggruppo
                         columns.Group(g => g
                             .Title(title[0])
                             .HeaderHtmlAttributes(new { style = "text-align: center !important;" })
                             .Columns(h =>
                                {
                                    //secondo ciclo per creare il raggruppamento
                                    foreach (System.Data.DataColumn head in Model.Columns)
                                    {
                                        if (head.ColumnName.StartsWith(title[0]))
                                        {
                                            var he = h.Bound(head.ColumnName);
                                            he.Title(head.ColumnName.Remove(0, head.ColumnName.IndexOf("_") + 1));
                                            switch (head.DataType.FullName)
                                            {
                                                case "System.DateTime":
                                                    he.Format("{0:dd/MM/yyyy}");
                                                    he.Width(40);
                                                    he.HtmlAttributes(new { style = "text-align: right !important;" });
                                                    break;
                                                case "System.Int32":
                                                    he.Width(60);
                                                    he.HtmlAttributes(new { style = "text-align: right !important;" });
                                                    break;
                                                case "System.Boolean":
                                                    he.Width(55);
                                                    break;
                                                default:
                                                    he.Width(200);
                                                    he.HtmlAttributes(new { style = "text-align: left !important;" });
                                                    break;
                                            }
                                            //inserisco la colonna nella collezione di quelle già elaborate
                                            columnElaborated.Add(head.ColumnName);
                                        }
                                    }
                                }
                             )
                         );
                     }
                 }
                 else
                 {
                     //se la colonna non è da raggruppare
                     var c = columns.Bound(column.ColumnName);
                     columnElaborated.Add(column.ColumnName);
                     switch (column.ColumnName)
                     {
                         case "civID":
                             c.ClientTemplate(@"
                <input type='checkbox' id='#: civID #' #= IsExpectedPreventiveMaintenance ? checked='checked':'' # name='SelectedcivID' class='checkbox' />"
         ).HeaderTemplate(@"<label><strong><input type='checkbox' onclick='checkAll(this)'/>All</strong></label>").Sortable(false).Filterable(false);
                             break;
                         case "IsExpectedPreventiveMaintenance":
                             c.Hidden(true);
                             break;
                         case "InventoryNumber":
                             //c.Locked(true);
                             break;
                         default:
                             //c.Title(column.ColumnName.Remove(0, 4));
                             break;
                     }
                     switch (column.DataType.FullName)
                     {
                         case "System.DateTime":
                             c.Format("{0:dd/MM/yyyy}");
                             c.Width(40);
                             c.HtmlAttributes(new { style = "text-align: right !important;" });
                             break;
                         case "System.Int32":
                             c.Width(60);
                             c.HtmlAttributes(new { style = "text-align: right !important;" });
                             break;
                         case "System.Boolean":
                             c.Width(55);
                             break;
                         default:
                             c.Width(200);
                             c.HtmlAttributes(new { style = "text-align: left !important;" });
                             break;
                     }
                     if (column.DataType.FullName == "System.DateTime")
                     {
                         c.Format("{0:dd/MM/yyyy}");
                         c.Width(50);
                     }
 
                 }
             }
         }
     })
            //Commentati per ragioni stilistiche
    .HtmlAttributes(new { style = "height: 700px;  width: 1000x; " })
    .Scrollable()
            //attributi della griglia
    .Groupable()
    .Filterable(ftb => ftb
        .Mode(GridFilterMode.Row)
        .Operators(operators => operators
        .ForString(str => str
            //riscrivo i modi di filtrare
            .Clear()
            .Contains("Contiene")
            .IsEqualTo("Uguale")
        )
        ))
    .Sortable(sort => sort.SortMode(GridSortMode.MultipleColumn))
    .ColumnMenu()
    .Resizable(rsb => rsb.Columns(true))
    .Reorderable(r => r.Columns(true))
    .Pageable(paging => paging
        .Refresh(true)
        .PageSizes(true)
        .PageSizes(pages)
        .ButtonCount(5)
    )
    .Events(evt => evt
        .DataBound("onDataBound")
    )
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .Model(model =>
            {
                var id = Model.Columns[0].ColumnName;
                model.Id(id);
                foreach (System.Data.DataColumn column in Model.Columns)
                {
                    var field = model.Field(column.ColumnName, column.DataType);
                    field.Editable(false);
                }
            })
        .Read(read => read.Action("Items_Read", "Calendar"))
     )
    )
</div>
<div class="k-edit-form-container buttons-container">
    @(Html.Kendo().Button()
            .Name("setInventoryButton")
            .Icon("tick")
            .Content("Ok")
            .Events(ev => ev.Click("VerifyChecked"))
    )
    @(Html.Kendo().Button()
            .Name("setCancelButton")
            .Icon("cancel")
            .Content("Cancel")
            .Events(ev => ev.Click("CloseInventoryWindow"))
    )
     
</div>

 

Thank you in advance

1 Answer, 1 is accepted

Sort by
0
Lorenzo
Top achievements
Rank 1
answered on 15 Oct 2015, 10:20 AM

 

Hi guys,

 I solved it. The field is correctly bind to the underlying model, however the function is not updating it correctly. By insert the instruction 

$("#inventoryItems").val(checked).trigger("change");

all works fine.

 Regards

Tags
Scheduler
Asked by
Lorenzo
Top achievements
Rank 1
Answers by
Lorenzo
Top achievements
Rank 1
Share this question
or