Telerik Forums
UI for ASP.NET MVC Forum
1 answer
234 views

Hi there,

I want a chart similiar to the one attached with this thread. Currently I am using scatter chart for my purpose but it would be great if I could get it colored like the attached screenshot.

Any help would be greatly appreciated.

 

 

Patrick | Technical Support Engineer, Senior
Telerik team
 answered on 18 Aug 2016
17 answers
478 views

Hi guys is it possible to add upload control inside subgrid with clientdetailtemplate?because after adding the control the main grid it nolonger loads the data, please see below the code 

<div  style="clear:both;  position:relative; padding-top: 10px">
 
@(Html.Kendo().Grid<KendoUIApp1_Test.Models.IncidentsViewModel>()
              .Name("grid")
          
 
              .Columns(colums =>
              {
                   * http://www.telerik.com/blogs/kendo-ui-r1-2016-webinar-wrapup
                   */
                  colums.Bound(p => p.DepartmentID).Hidden(true);
                  colums.Bound(p => p.SiteAuditID).Hidden(true);
                  colums.Bound(p => p.QuestionID).Hidden(true);
 
                  colums.Bound(p => p.StatusName).Title("Status").Filterable(false).ClientTemplate(
                                                                                                   "# if (StatusID === 1 ) { #" +
                                                                                                     "<span class='CBdrawingstatusGreen'>#:StatusName#</span>" +
                                                                                                  "# } else if (StatusID === 2 ) { #" +
                                                                                                      "<span class='CBdrawingstatusYellow'>#:StatusName#</span>" +
                                                                                                  "# } else { #" +
                                                                                                      "<span class='CBdrawingstatusred'>#:StatusName#</span>" +
                                                                                                  "# } #"
 
                                                                                                );
                  colums.Bound(p => p.ReferenceNo).Title("ReferenceNo").Filterable(true);
                  colums.Bound(p => p.IncidentDate).Title("IncidentDate").ClientTemplate("#= kendo.format('{0:MM/dd/yyyy HH:mm:ss}',kendo.parseDate(IncidentDate)) #"); //.Filterable(model => model.UI("IncidentDateFilter"));
                  colums.Bound(p => p.AccountName).Title("Airport").Filterable(false).Width(200);
                  colums.Bound(p => p.SiteName).Title("Site").Filterable(false);
                  colums.Bound(p => p.Department1).Title("Department").Filterable(false);
                  colums.Bound(p => p.Description).Title("Description").Filterable(false);
                  colums.Bound(p => p.Comments).Title("Comments").Filterable(false);
                  colums.Bound(p => p.ContactName).Title("CurrentAssignedContact").Filterable(false).Width(200);
                  colums.Bound(p => p.FirstName).Title("CurrentAssignedUser").Filterable(false);
                  colums.Bound(p => p.IncidentID).ClientTemplate("<a class='k-button' href='" + Url.Action("GetPDF", "Home") + "?IncidentID=#= IncidentID #'" + "> <span span class='k-icon k-i-pdf''></span>Get Incident Pdf</a>").Title("Download PDF").Filterable(false);
                
                  colums.Command(cmd =>
                  {
                      cmd.Edit();
                      //cmd.Custom("Upload").Click("onCustomCommandClick");
                  });
 
              })
              .ClientDetailTemplateId("client-template")
          .Filterable(filterable => filterable
            .Extra(true)
            .Operators(operators => operators
                .ForString(str => str.Clear()
                    .StartsWith("Starts with")
                    .IsEqualTo("Is equal to")
                    .IsNotEqualTo("Is not equal to")
 
                ))
            )
 
    .HtmlAttributes(new { style = "height:550px;" })
    .DataSource(datasource => datasource
    .Ajax() //Configure the grid data source
     
    .Events(Eevents => Eevents.RequestEnd("OnChangeRefresh"))
    .Model(model =>
    {
        model.Id(m => m.IncidentID);
 
 
    })
    .Read(read =>
    {
        read.Action("GetIncidents", "Home").Data("IncidentsFilter");
    })// set the action method which will return the data in json format
 
    .Update(update => update.Action("Incidents_Update", "Home"))
    )
 
    .Navigatable()
    .Groupable()
    .Pageable()
    .Reorderable(reorder => reorder.Columns(true))
    .Sortable()
    .Scrollable()
        .Events(events =>
        {
            events.Save("onIncidentUserAssign");
            // events.Save("onStatusChange");
 
        })
 
            .Events(eEvents => eEvents.Edit("disableOnEdit"))
            .Events(x => x.DataBound("onDataBound"))
        //.Events(events =>
        //{
        //  events.Save("onStatusChange");
        //   // events.Save("onStatusChange");
 
        //})
 
 
    .Editable(ed => ed.Mode(GridEditMode.PopUp).TemplateName("Incidents")
                                               .Window(w => w.Animation(true)
                                               .Scrollable(false)
                                               .Name("editWindow")))
     
 
        )
    
    </div>
 
<script id="client-template" type="text/x-kendo-template">
    @(Html.Kendo().Grid<KendoUIApp1_Test.Models.AuditPicIncidentModel>()
        .Name("Grid_#=SiteAuditID#")
          .ToolBar(toolbar => toolbar.Template(
     
        @<text>
            @(Html.Kendo().Upload()
                  .Name("files")
                  .Async(a => a.Save("Save", "Home"))
                  .Events(e => e.Success("onUploadSuccess"))
                  .ShowFileList(false) // Hide the file list as we're displaying uploaded files in the Grid
            )
          </text>
    ))
        .Columns(columns =>
                            {
                                columns.Bound(b => b.FileName).Title("File Name");
                                columns.Bound(b => b.PictureCaption).Title("Picture Caption").HtmlAttributes(new { style = "overflow: hidden;text-overflow: ellipsis;white-space:nowrap;" }).EditorTemplateName("ConfigurationSettingItemEditor");
                          
                                columns.Command(command => command.Destroy()).Width(100);
                                 
                            }
                )
        .Sortable()
        .Pageable(c => c.PageSizes(new int[] { 10, 20, 50, 100 }))
        .Scrollable()
        .HtmlAttributes(new { style = "height:430px;" })
        .DataSource(datasource => datasource
                    .Ajax()
                      .Model(model =>
                            {
                                model.Id(q => q.AuditResultPictureID);
                                //model.Field(q => q.KeyValue).Editable(true);
                                //model.Field(q => q.Enabled).DefaultValue(true);
  
                            })
                    .PageSize(10)
                    .ServerOperation(true)
                    .Read(read => read.Action("ConfigurationItem_Read", "Home", new { SiteAuditID = "#=SiteAuditID#", QuestionID = "#=QuestionID#" }))
                    .Destroy(update => update.Action("FilesDestriy", "Home"))
                     )
                      
                      
        .ToClientTemplate()
          
          
  
  
    )
 
   
  
</script>

Marc Plaxton-Harrison
Top achievements
Rank 1
 answered on 18 Aug 2016
1 answer
259 views

Hi i have an task scheduller

And would like to get ID of current task using  CustomEditorTemplate 

@Model.TaskID is always equals to 0

.Editable(editable =>
                  {
                      editable.TemplateName("CustomEditorTemplate");
                  })

 @(Html.Kendo().Scheduler<TaskViewModel>()
                  .Name("schedule")
                  .Date(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day))
                  .StartTime(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 9, 00, 00))
                  .EndTime(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 18, 00, 00))
                  .HtmlAttributes(new {@class = "ra-section"})
                 
                  .Views(views =>
                  {
                      views.DayView(dayView => dayView.Selected(true));
                      views.WeekView();
                      views.MonthView();
                      views.AgendaView();
                  })
                  .Editable(editable =>
                  {
                      editable.TemplateName("CustomEditorTemplate");
                  })
                  .Timezone("Etc/UTC")

                  .DataSource(dataSource => dataSource
                      .Model(m =>
                      {
                          m.Id(f => f.TaskID);
                          m.Field(f => f.Title);
                          m.Field(f => f.Start);
                          m.Field(f => f.End);
                          m.Field(f => f.Description);
                          m.Field(f => f.RecurrenceID);
                          m.Field(f => f.RecurrenceRule);
                          m.Field(f => f.RecurrenceException);
                          m.Field(f => f.IsAllDay);
                          m.Field(f => f.StartTimezone);
                          m.Field(f => f.EndTimezone);
                      })
                      .Events(e => e.Error("error_handler"))
                      .Read("ChargerTous", "TaskScheduler")
                      .Create("Ajouter", "TaskScheduler")
                      .Update("Modifier", "TaskScheduler")
                      .Destroy("Supprimer", "TaskScheduler")
                  )
                  )

And I have a custom editor template

@model Gloe.Web.Website.ViewModel.TaskViewModel
@{
    ViewContext.FormContext = new FormContext();
}

<div data-container-for="grid" class="k-edit-field">

        @(Html.Kendo().Grid<Gloe.Web.Website.ViewModel.TaskScheduler.PrelevementViewModel>()
    .Name("grid")
    .Columns(columns =>
    {

        columns.Bound(p => p.NomPrelevement).ClientTemplate("\\#= productDetails(data) \\#")
          .ClientFooterTemplate("count : \\#=count \\#")
            .ClientGroupFooterTemplate("count : \\#=count \\# ");
        columns.Bound(p => p.ValeurPrelevement).Width(120)
        .ClientFooterTemplate("Sum: \\#=sum\\# ")
            .ClientGroupFooterTemplate("Sum: \\#=sum\\# ");

        columns.Command(command => { command.Edit(); command.Destroy(); }).Width(250);

    })

    .ToolBar(toolbar => toolbar.Create())
    .Editable(editable => editable.Mode(GridEditMode.InLine))
    .Events(events => events.Change("onChange").DataBound("onDataBound").DataBinding("onDataBinding"))

    .DataSource(dataSource => dataSource
        .Ajax()
         .Aggregates(aggregates =>
         {
             aggregates.Add(p => p.NomPrelevement).Count();
             aggregates.Add(p => p.ValeurPrelevement).Sum();
         })
        .PageSize(20)

        .Model(model =>
        {
            model.Id(l => l.IdPrelevement);
            model.Field(field => field.IdPrelevement).Editable(false);
            model.Field(field => field.NomPrelevement).Editable(false);
            model.Field(field => field.ValeurPrelevement);
        })
        .Create(update => update.Action("EditingInline_Create", "RapportAnalyse").Data("additionalInfo"))
        .Read(read => read.Action("EditingInline_Read", "RapportAnalyse").Data("GetTaskID"))
        .Update(update => update.Action("EditingInline_Update", "RapportAnalyse"))
        .Destroy(update => update.Action("EditingInline_Destroy", "RapportAnalyse"))
    )
        )
    </div>
</div>

@{
    ViewContext.FormContext = null;
}

Vladimir Iliev
Telerik team
 answered on 18 Aug 2016
3 answers
180 views

Hello I have a page with a listview, when an item is selected, 5 grid are filtered, nested on each grid is a subgrid (in the images attached you could see it better) in this subgrid one column has a combobox, I need that when an item on the listview is selected this combobox rebind the data. But it only happens when the method is called when the page is loaded, even the method is called and executed with out errors the combobox remains with the original data.

Below is the combobox:

@model ContabilidadSinLios.Models.CatalogoCuentasViewModel
 
 @(Html.Kendo().ComboBox()
        .Name("CatalogoCuentas")
        .DataValueField("CatalogoCuentaId")
        .DataTextField("Nombre")
        .Height(100)
        .BindTo((System.Collections.IEnumerable)ViewData["catalogos"])
        .HtmlAttributes(new { style = "width: 330px !important; font-size: 11px; " })
        .Suggest(true)
        .MinLength(1)
        .Filter(FilterType.Contains)
    )

And here is the one of the grids:

@(Html.Kendo().Grid<EgresosViewModel>()
                   .Name("cdfie")
                   .Scrollable(s => s.Enabled(true).Height("auto"))
                   .AutoBind(false)
                   .Columns(columns =>
                   {
                       columns.Template(t => { })
                       .ClientTemplate("#=UUID#")
                       .Title("UUID").Hidden(true)
                       .Width(100);
                       columns.Bound(f => f.EstatusSAT).Filterable(false).Title("Estatus SAT").Width(80);
                       columns.Bound(f => f.FechaEmision).Title("Fecha Emisión").Filterable(false).Format("{0:d}").Width(100);
                       columns.Bound(f => f.RFCReceptor).Hidden(true);
                       columns.Bound(f => f.RFCEmisor).Title("RFC Emisor").Width(120);
                       columns.Bound(f => f.NombreEmisor).Title("Nombre Emisor").Width(250);
                       columns.Bound(f => f.SubTotal).Filterable(false).Width(80).Format("{0:c}");
                       columns.Bound(f => f.Descuento).Filterable(false).Width(80).Format("{0:c}");
                       columns.Bound(f => f.IVA16).Title("IVA 16%").Filterable(false).Width(80).Format("{0:c}");
                       columns.Bound(f => f.IEPS).Filterable(false).Width(80).Format("{0:c}");
                       columns.Bound(f => f.RetenidoIVA).Filterable(false).Title("IVA Retenido").Width(120).Format("{0:c}");
                       columns.Bound(f => f.RetenidoISR).Filterable(false).Title("ISR Retenido").Width(120).Format("{0:c}");
                       columns.Bound(f => f.Total).Filterable(true).Width(120).Format("{0:c}");
                       columns.Bound(f => f.MetodoPago).Filterable(false).Width(120).Title("Método de Pago");
                   })
                   .Events(e =>
                        {
                            e.DataBound("onDataBoundEgreso");
                        })
                   .Pageable(pageable => pageable.Refresh(true))
                   .Sortable()
                   .Selectable()
                   .Navigatable()
                   .Resizable(resize => resize.Columns(true))
                   .ClientDetailTemplateId("ConceptosEgresos_DetailTemplate")
                   .DataSource(dataSource => dataSource
                   .Ajax()
                   .PageSize(15)
                   .Model(m =>
                   {
                       m.Id(f => f.UUID);
                       m.Field(f => f.UUID).Editable(false);
                       m.Field(f => f.FechaEmision).DefaultValue(DateTime.Today);
                   })
                   .Events(events => events.Error("error_handler"))
                   .Sort(s => s.Add(f => f.FechaEmision).Descending())
                   .Read(read => read.Action("CFDISEgreso_Read", "SinLios"))
                   )
               )
               <script id="ConceptosEgresos_DetailTemplate" type="text/x-kendo-tmpl">
                   <h4>Detalle para CFDI \\##=UUID# </h4>
                   @(Html.Kendo().Grid<ConceptosViewModel>()
                       .Name("order_details#=UUID#")
                       .Columns(columns =>
                       {
                           columns.Command(command =>
                           {
                               command.Edit().UpdateText("Actualizar").Text("Editar");
                           }).Width(100);
                           columns.Bound(f => f.Id).Hidden(true);
                           columns.Bound(f => f.Cantidad).Width(50);
                           columns.Bound(f => f.ValorUnitario).Format("{0:c}").Width(80);
                           columns.Bound(f => f.Descripcion).Encoded(false)
                           .Title("Descripción").Filterable(false).Width(250);
                           columns.Bound(f => f.Importe).Format("{0:c}").Width(80);
                           columns.Bound(f => f.Deducible).ClientTemplate("<span> \\#= Deducible ? 'Si' : 'No' \\#</span>")
                           .Title("Deducible").Width(80);
                           columns.Bound(f => f.DeducibleAnual).ClientTemplate("<span> \\#= DeducibleAnual ? 'Si' : 'No' \\#</span>")
                           .Title("Deducible Anual").Width(100);
                           columns.Bound(f => f.MontoDeducible).Title("Monto Deducible").Format("{0:c}").Width(100);
                           columns.Bound(f => f.CatalogoCuentaId).ClientTemplate("\\#=CatalogoCuentas.Nombre\\#").Title("Catálogo de Cuentas")
                           .Filterable(false).Width(200).ClientFooterTemplate("Total Deducible:");
                           columns.Bound(f => f.CatalogoCuentas.Nombre);
                           //.Hidden(true);
                           columns.Template(f => new { })
                           .Title("Total Deducible")
                           .ClientTemplate("\\#=kendo.toString(GetOrderItemPrice(data), \"c\")\\#")
                           .ClientFooterTemplate("<span name='sum'></span>").Width(120);
                           columns.Bound(f => f.IVA16).ClientTemplate("<span> \\#= IVA16 ? 'Si' : 'No' \\#</span>")
                         .Filterable(false).Title("IVA 16%").Width(80);
                           columns.Bound(f => f.IVA0).ClientTemplate("<span> \\#= IVA0 ? 'Si' : 'No' \\#</span>")
                           .Filterable(false).Title("IVA 0%").Width(80);
                           columns.Bound(f => f.IVAExento).ClientTemplate("<span> \\#= IVAExento ? 'Si' : 'No' \\#</span>")
                           .Filterable(false).Title("Exento IVA").Width(80);
                           columns.Bound(f => f.VisiblePara).Width(80);
 
                       })
                       .Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("ConceptosEditor"))
                       .Events(e =>
                       {
                           e.DataBound("onOrderDetailsEgresoDataBound");
                       })
                       .Selectable()
                       .Pageable(pageable => pageable.Refresh(true))
                       .Navigatable()
                       .Resizable(resize => resize.Columns(true))
                       .DataSource(dataSource => dataSource
                       .Ajax()
                       .Model(model =>
                       {
                           model.Id(concepto => concepto.Id);
                           model.Field(concepto => concepto.Id).Editable(false);
                           model.Field(concepto => concepto.Descripcion).Editable(false);
                           model.Field(concepto => concepto.Unidad).Editable(false);
                           model.Field(concepto => concepto.Cantidad).Editable(false);
                           model.Field(concepto => concepto.UUID).Editable(false);
                           model.Field(concepto => concepto.IVA16).DefaultValue(false);
                           model.Field(concepto => concepto.IVA0).DefaultValue(false);
                           model.Field(concepto => concepto.IVAExento).DefaultValue(false);
                           model.Field(concepto => concepto.Importe).Editable(true);
                           model.Field(concepto => concepto.ValorUnitario).Editable(false);
                           model.Field(concepto => concepto.CatalogoCuentaId).Editable(true);
                           model.Field(concepto => concepto.CatalogoCuentas).DefaultValue(ViewData["catalogos"] as CatalogoCuentasViewModel).Editable(true);
                           model.Field(concepto => concepto.Ano).Editable(true);
                           model.Field(concepto => concepto.Mes).Editable(true);
                           model.Field(concepto => concepto.VisiblePara).Editable(true);
                       })
                       .Events(events => events.Error("error_handler")
                       .Sync("sync_handler"))
                       .Read(read => read.Action("Conceptos_Read", "SinLios", new { UUID = "#=UUID#", Ano = "#=Ano#", Mes = "#=Mes#", VisiblePara = "#=RFCReceptor#" }))
                       .Update(update => update.Action("UpdateConcepto", "SinLios")))
                       .ToClientTemplate()
                   )
               </script>

And the code for populate the catalogo de cuentas:

public void PopulateCatalogoCuentas(string RFC)
{
  IOrderedEnumerable<CatalogoCuentasViewModel> catalogos = _context.CatalogoDeCuentasRFC(RFC)
               .Select(c => new CatalogoCuentasViewModel
               {
                   CatalogoCuentaId = c.CatalogoCuentaId,
                   Nombre = c.Nombre + " - " + c.CatalogoCuentaId
               }).ToList()
               .OrderBy(e => e.Nombre);
 
           bool existe = (from item in catalogos select item).Count() > 0;
 
           if (existe)
           {
               ViewData["catalogos"] = catalogos;
               ViewData["defaultCatalogo"] = catalogos.FirstOrDefault();
           }
           else
           {
               ViewData.Clear();
               IOrderedEnumerable<CatalogoCuentasViewModel> todoCatalogo = _catalogoCuentasRepository.FindAll()
               .Select(c => new CatalogoCuentasViewModel
               {
                   CatalogoCuentaId = c.CatalogoCuentaId,
                   Nombre = c.Nombre + " - " + c.CatalogoCuentaId
               })
               .OrderBy(e => e.Nombre);
 
               ViewData["catalogos"] = todoCatalogo;
               ViewData["defaultCatalogo"] = todoCatalogo.First();
           }
       }

 

 

Viktor Tachev
Telerik team
 answered on 17 Aug 2016
3 answers
137 views

hi , I have a  pretty simple requirement for doing that I have written the following code.

 

grid is in paymentviewgrid cshtml which is being called in the index page, below

 

     function BuGridSaveChange(e)
    {   
        if (manualList.length > 0)
        {
            var isRecordExist = false;
            var totalRecords = manualList;
            for (var i = 0; i <= totalRecords.length - 1; i++)
            {
                if (manualList[i].PoId == e.model.PoId && manualList[i].RCUId == e.model.RCUId && manualList[i].MrrId == e.model.MrrId
                    && manualList[i].BU_Id == e.model.BU_Id
                    && manualList[i].REUId == e.model.REUId)
                {
                    manualList[i].ManualAmountPaid = e.model.ManualAmountPaid;
                    isRecordExist = true;
                }
            }
            if (isRecordExist == false)
            {
                var singleSrObj = new Object();
                singleSrObj.PoId = e.model.PoId;
                singleSrObj.REUId = e.model.REUId;
                singleSrObj.RCUId = e.model.RCUId;
                singleSrObj.MrrId = e.model.MrrId;
                singleSrObj.ManualAmountPaid = e.model.ManualAmountPaid;
                singleSrObj.BU_Id = e.model.BU_Id;
                manualList.push(singleSrObj);
            }
        }
        else
        {
            var singleNewSrObj = new Object();
            singleNewSrObj.PoId = e.model.PoId;
            singleNewSrObj.REUId = e.model.REUId;
            singleNewSrObj.RCUId = e.model.RCUId;
            singleNewSrObj.MrrId = e.model.MrrId;
            singleNewSrObj.ManualAmountPaid = e.model.ManualAmountPaid;
            singleNewSrObj.BU_Id = e.model.BU_Id;
            manualList.push(singleNewSrObj);
        }
    }

    function RequestEnd(e)
    {         
     if (e.response.Errors == null )      
        {
            if ((e.type === "update" )&& e.response.Data.length > 0)
            {
                if (manualList.length > 0)
                {
     
                    var isAmountEntered = false;
     
                    for (var i = 0; i <= manualList.length - 1; i++)
                    {
                        if (manualList[i].ManualAmountPaid != null && manualList[i].ManualAmountPaid >= 0)
                        {
                            isAmountEntered = true;
                        }
                        if (manualList[i].PoId == e.response.Data[0].PoId && manualList[i].RCUId == e.response.Data[0].RCUId && manualList[i].MrrId == e.response.Data[0].MrrId
                            && manualList[i].BU_Id == e.response.Data[0].BU_Id
                            && manualList[i].REUId == e.response.Data[0].REUId)
                        {
                            manualList[i].ManualAmountPaid  = e.response.Data[0].ManualAmountPaid;
                            document.getElementById("approvePaymentButton").disabled = true;
                            document.getElementById("poSummaryPaymentButton").disabled = true;
                        }
                    }
                    if (isAmountEntered == true)
                    {
                        document.getElementById("recreatePaymentButton").disabled = false;
                    }
                    else
                    {
                        document.getElementById("recreatePaymentButton").disabled = true;
                        document.getElementById("approvePaymentButton").disabled = false;
                        document.getElementById("poSummaryPaymentButton").disabled = false;
                    } 
                }
            }
           
        }
        else if (e.response.Errors != null && e.type === "update")
        {       
         document.getElementById("recreatePaymentButton").disabled = true;
        }
    }

 

 

the issue is while coding this

I received e.type== "update " and in update function I have written some other businesslogic

and after testing and implementation with no code changes , I started receiving e.type== "create" where I cannot see update atall.

due to this I cannot call the logic that was in update function from controller.

 

could you please help on this

 

 

Konstantin Dikov
Telerik team
 answered on 17 Aug 2016
7 answers
2.2K+ views

Lets say i have a grid with three columns A,B and C. Also lets assume the grid is Batch so that mean In-Cell edit. If a user is entering a row and and the user enters the same number in both cells A and B, then I want cell C to have a background color of red.

Basically this is a conditional on edit of two cells and if they meet the condition a third cell's background color is changed. This is not needed during databound because it's a simple batch that will clear the entries once saved some no data binding taking place if that makes sense.

 

I tired using a clientTemplate but it seems to work only on a new record or during databinding.  If they edit an existing row it needs to perform the check.

 

Any suggestions appreciated

I'm assuming on the Save event (in-cell), but how do you get and set the cell background color of C?
Greg
Top achievements
Rank 1
 answered on 16 Aug 2016
9 answers
2.8K+ views

I would like to send a viewModel selected with edit "Edit" action grid to update this row data in controller side .
I would like then to send back the new version of row data : update Popup and datasource grid.

For now, the ajax post to send the edit row doesn't work fine. The data propertie of ajax call return an javascript Error.

Do you have a suggestion ? Thanks.

View :

 

@(Html.Kendo().Grid<KendoGridAjaxEditing.Models.ProductViewModel>()
      .Name("grid")
      .Columns(columns =>
      {
          columns.Bound(product => product.ProductName);
          
          columns.Bound(product => product.UnitsInStock).Width(250);
          columns.Command(commands =>
          {
              commands.Edit(); // The "edit" command will edit and update data items
              commands.Destroy(); // The "destroy" command removes data items
          }).Title("Commands").Width(200);
      })
        .Filterable(ftb => ftb.Mode(GridFilterMode.Row))
       .Scrollable()
       .Groupable()
        .Events(e =>
        {
             e.Edit("onRequestEdit"); // Ajax Call to update
        })
      .Editable(editable => editable.Mode(GridEditMode.PopUp)) // Use inline editing mode
      .DataSource(dataSource => dataSource
            .Ajax()
            .Model(model =>
            {
                model.Id(product => product.ProductID); // Specify the property which is the unique identifier of the model
                model.Field(product => product.ProductID).Editable(false).DefaultValue(0); // Make the ProductID property not editable
            })
            .Events(events =>
                    {
                    events.Error("onError");   
             })
            .ServerOperation(false)
            .Create(create => create.Action("Products_Create", "Home")) // Action invoked when the user saves a new data item
            .Read(read => read.Action("Products_Read", "Home"))  // Action invoked when the grid needs data
            .Update(update => update.Action("Products_Update", "Home"))  // Action invoked when the user saves an updated data item
            .Destroy(destroy => destroy.Action("Products_Destroy", "Home")) // Action invoked when the user removes a data item
      )
      .Pageable()
)

JavaScript (ajax call) :

 

function onRequestEdit(arg) {
        alert("onRequestEdit : Edit row");
         
        var griddata = $("#grid").data("kendoGrid");
         
        var uid = $(".k-edit-form-container").closest("[data-role=window]").data("uid");
        kendoConsole.log('onRequestEdit : Edit uid :' + uid);
        var model = $("#grid").data("kendoGrid").dataSource.getByUid(uid);
        // Show row value with currente model -> OK
        kendoConsole.log("onRequestEdit : Edit model : " + model.ProductID + ":" + model.ProductName);
        // Show row value with argument -> OK
kendoConsole.log("onRequestEdit : Edit argument : " + arg.model.ProductID + ":" + arg.model.ProductName);
        $.ajax({
            url: '@Url.Action("Products_CheckLock", "Home")',
            type: 'POST',
            datatype: 'json',
            contentType: "application/json; charset=utf-8",
            //data: JSON.stringify({ product: arg.model.data() }), // Return a javaScript Error
            //data: JSON.stringify({ product: arg.model() }), // Return a javaScript Error
            //data: JSON.stringify({ product: arg.model.dataSource(this) }), // Return a javaScript Error
            //data: JSON.stringify({ product: arg.model.dataSource.data() }), // Return a javaScript Error
            data: JSON.stringify({ product: arg.model.dataSource.data() }), // Return a javaScript Error
            success: function (result) {
                // Update record in Popup Edit
                // Is it a good way ?
                var grid = $("#grid").data("kendoGrid");
                var dataSource = new kendo.data.DataSource({
                        data: result.Data
                });
                grid.setDataSource(dataSource);
                grid.dataSource.refresh();
            },
            error: function () { alert('SM : Error Edit row'); }
        })
    }

Controller :

public ActionResult Products_CheckLock([DataSourceRequest]DataSourceRequest request, ProductViewModel[] product)
        //public ActionResult Products_CheckLock([DataSourceRequest]DataSourceRequest request, String product)
        {
            if (ModelState.IsValid)
            {
                using (var northwind = new NorthwindEntities())
                {
                    // Create a new Product entity and set its properties from the posted ProductViewModel
                    var entity = new Product
                    {
                        ProductID = product[0].ProductID,
                        ProductName = "Last_Version-" + product[0].ProductName,
                        UnitsInStock = product[0].UnitsInStock
                    };
                }
            }
            // Return the removed product. Also return any validation errors.
            return Json(new[] { product }.ToDataSourceResult(request, ModelState));
        }

 

Dimo
Telerik team
 answered on 15 Aug 2016
5 answers
696 views

Hello,

 

I am having an issue accessing a field that exists in the model for the clientdetailtemplate it keeps searching the parent grids model and not the clientdetail:

below in the template grid the line columns.Bound(c => c.PurchaseOrder).ClientTemplate("<button class='k-button' onclick=\"showDetails('#=PurchaseOrder#','#=DC#')\">Item Details</button>").Title("Item Details"); fails with "Uncaught ReferenceError: DC is not defined" but i can swith DC in that line to PODateShort and it send that number to the onclick function. so im assuming that #=field# can only reference the main grids model but i need to get the DC from the secondary grid so that i can send that to the onclick and search for all the items in that po for that dc.

Any help would be greatly appreciated.

 

@(Html.Kendo().Grid<PurchaseOrderResults>()
              .Name("POGrid")
              .Resizable(resize => resize.Columns(true))
              .Reorderable(reorder => reorder.Columns(true))
              .Filterable()
              .HtmlAttributes(new { style = "height:600px;" })
              .Columns(columns =>
              {
                  columns.Bound(c => c.PurchaseOrder);
                  columns.Bound(c => c.PODateShort);
                  columns.Bound(c => c.RequestDateShort);
                  columns.Bound(c => c.ActualShipDateShort);
                  columns.Bound(c => c.ArrivalDateShort);
              })
                .Scrollable()
                .ClientDetailTemplateId("POtemplate")
                .Sortable()
                .Pageable(builder => builder.PageSizes(new[] { 10, 50, 100 }))
                .DataSource(datasource => datasource
                                        .Ajax()
                                        .PageSize(10)
                                        .Read(read => read.Action("GetPOSearch", "PO", new { SiteID = Model.SiteID, PONumbers = Model.PONumbers }))
                                        )
    )
</div>
<script id="POtemplate" type="text/kendo-tmpl">
    @(Html.Kendo().Grid<PurchaseOrderDCResults>()
            .Name("POGrid_#=PurchaseOrder#") // template expression, to be evaluated in the master context
            .Columns(columns =>
            {
                columns.Bound(c => c.PurchaseOrder);
                columns.Bound(c => c.DC);
                columns.Bound(c => c.OrderDollars);
                columns.Bound(c => c.UnitsOrdered);
                columns.Bound(c => c.PurchaseOrder).ClientTemplate("<button class='k-button' onclick=\"showDetails('#=PurchaseOrder#','#=DC#')\">Item Details</button>").Title("Item Details");
            })
            .DataSource(dataSource => dataSource
                .Ajax()
                .PageSize(10)
                .Read(read => read.Action("GetPODCSearch", "PurchaseOrder", new { SiteID = Model.SiteID, PONumber = "#=PurchaseOrder#" }))
            )
            .Pageable(builder => builder.PageSizes(new[] { 10, 50, 100 }))
            .Sortable()
            .ToClientTemplate()
    )
</script>

Dimiter Madjarov
Telerik team
 answered on 15 Aug 2016
2 answers
264 views

Hello,

I am having some trouble using custom callbacks for PasteCleanup, Deserialization or Serialization. Whatever input string I give as the custom callback, be it a function name or declaration, just gets double quoted in the editor configuration javascript that is generated and is then seemly ignored. Unlike how setting an event callback works.

How do I setup an editor to use these features?

Sample code:

@(Html.Kendo().Editor()
    .Name("bloop")
    .PasteCleanup(e => e.Custom("onPaste"))
    .Deserialization(e => e.Custom("onDeserialization"))
    .Serialization(e => e.Custom("onSerialization"))
    .Events(e => e.Change("onChange"))
)
 
<script type="text/javascript">
    function onPaste(html) {
        console.log('onPaste');
 
        return html;
    }
 
    function onSerialization(html) {
        console.log('onSerialization');
 
        return html;
    }
 
    function onDeserialization(html) {
        console.log('onDeserialization');
 
        return html;
    }
 
    function onChange() {
        console.log('onChange');
    }
</script>

 

Using that above code Html.Kendo().Editor() is generating the following javascript when it executes:

jQuery(function(){jQuery("#bloop").kendoEditor({"change":onChange,"deserialization":{"custom":"onDeserialization"},"pasteCleanup":{"custom":"onPaste"},"serialization":{"custom":"onSerialization"},"tools":[{"name":"formatting"},{"name":"bold"},{"name":"italic"},{"name":"underline"},{"name":"justifyLeft"},{"name":"justifyCenter"},{"name":"justifyRight"},{"name":"insertUnorderedList"},{"name":"insertOrderedList"},{"name":"outdent"},{"name":"indent"},{"name":"createLink"},{"name":"unlink"},{"name":"insertImage"},{"name":"createTable"},{"name":"addColumnLeft"},{"name":"addColumnRight"},{"name":"addRowAbove"},{"name":"addRowBelow"},{"name":"deleteRow"},{"name":"deleteColumn"}]});});

Note how onDeserialization is double quoted where onChange is not.

Using R2 2016 SP2 (2016.2.714) with MVC4.

Thank you

CWS
Top achievements
Rank 1
 answered on 12 Aug 2016
2 answers
119 views
In the editor, Is there a way to relocate the tool bar to the bottom left as opposed to the upper left?
Mark
Top achievements
Rank 1
 answered on 12 Aug 2016
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
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
Top achievements
Rank 1
Iron
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
ivory
Top achievements
Rank 1
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
YF
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Top achievements
Rank 1
Iron
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
ivory
Top achievements
Rank 1
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
YF
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?