Telerik Forums
UI for ASP.NET MVC Forum
6 answers
203 views

if I change GridEditMode.PopUp to GridEditMode.InLine it works, but when it is in PopUp mode, it throws following error

The model item passed into the dictionary is of type 'OfficeGx.Pms.Model.WorkStatus', but this dictionary requires a model item of type 'System.Int32'.Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'OfficeGx.Pms.Model.WorkStatus', but this dictionary requires a model item of type 'System.Int32'.

Source Error: 

Line 1: @using OfficeGx.Pms.Model.NonDb Line 2: @(Html.Kendo().Grid<OfficeGx.Pms.Model.WorkStatus>() Line 3: .Name("WorkStatusGrid") Line 4: .Columns(columns =>
Source File: Status.cshtml    Line: 2 

Here is my Grid Code

@using OfficeGx.Pms.Model.NonDb
@(Html.Kendo().Grid<OfficeGx.Pms.Model.WorkStatus>()
      .Name("WorkStatusGrid")
      .Columns(columns =>
      {
          columns.Bound(c => c.Id);
          columns.Bound(c => c.Name);
          columns.Bound(c => c.Style.BackgroundColor).ClientTemplate("# if(typeof Style!='undefined') { #<span>#:Style.BackgroundColor#</span># } else { #''# }#");
          columns.Bound(c => c.Description).Width(150);
          columns.Bound(c => c.DisplayOrder);
          columns.Bound(c => c.CreatedDateUtc).Format("{0:dd/MM/yyyy HH:mm}");
          columns.Bound(c => c.ModifiedDateUtc).Format("{0:dd/MM/yyyy HH:mm}");
          columns.Bound(c => c.IsDefault).EditorTemplateName("BooleanForWorkConfigDefault")
              .HtmlAttributes(new { @class = "default-checkbox-status" });
          columns.Command(command =>
          {
              command.Edit().Text(" ");
              command.Destroy().Text(" ");
          });
      })
    //.Scrollable()
    .Groupable()
    .Sortable().ColumnMenu()
      .ToolBar(toolbar =>
      {
          toolbar.Create();
          //toolbar.Save();
      })
      .Editable(editable =>
                editable.Mode(GridEditMode.InLine)
                .Window(x => x.Width(600).Title("Add/Edit Status")))
      .Pageable(pageable => pageable
          .Refresh(true)
          .PageSizes(true)
          .ButtonCount(5))
      .Resizable(resize => resize.Columns(true))
      .Reorderable(reorder => reorder.Columns(true))
      .DataSource(dataSource => dataSource
          .Ajax()
          .Sort(sort => sort.Add(x => x.DisplayOrder).Ascending())
          .Batch(true)
          .Model(model =>
          {
              model.Id(x => x.Id);
              model.Field(c => c.Id).DefaultValue(0).Editable(false);
 
              model.Field(x => x.Name).Editable(true);
              //model.Field(x => x.Style).DefaultValue(new Style()).Editable(true);
              model.Field(x => x.Style.BackgroundColor).Editable(true);
              model.Field(x => x.DisplayOrder).Editable(true);
              model.Field(c => c.Description).Editable(true);
              model.Field(c => c.CreatedDateUtc).Editable(false);
              model.Field(c => c.ModifiedDateUtc).Editable(false);
          })
      .Events(events => events.Error("workConfig.gridErrorHandler"))
      .Read(read => read.Action("ReadStatus", "Config", new { area = "Pms" }))
      .Create(update => update.Action("AddStatus", "Config", new { area = "Pms" }))
      .Update(update => update.Action("UpdateStatus", "Config", new { area = "Pms" }))
      .Destroy(update => update.Action("DeleteStatus", "Config", new { area = "Pms" }))
      .PageSize(20)
      ))
Alex Hajigeorgieva
Telerik team
 answered on 10 Nov 2017
1 answer
9.4K+ views

I want to give something a data-target value in my grid results.  I used a client template to achieve this but I cannot give the data-target an identifier, as soon as I type data-target=''#mymodal' the system crashes and the grid breaks and fails to load.  Is there anyway to include a # in my client template that won't breakt he grid?

 

@(Html.Kendo().Grid<Kendo_Range_Test.ViewModels.VesselViewModel>()
      .Name("Grid")
      .Columns(columns =>
      {
          columns.Bound(c => c.owner_company);          
          columns.Bound(c => c.vessel_status);
          columns.Command(command => { command.Edit(); }).Width(180);
          columns.Bound(c => c.vessel_idx)
               .ClientTemplate(
               "<a href='" + Url.Action("Create", "Fixture") + "/#=vessel_idx #'" + ">Fixture</a>");
          columns.Bound(c => c.vessel_idx)
               .ClientTemplate(
               "<a data-toggle='modal' data-target='#myModal' href='" + Url.Action("Create", "Fixture") + "/#=vessel_idx #'" + ">Details</a>");
           
      }
      )
      .Editable(editable => editable.Mode(GridEditMode.InLine))
      .Pageable()
      .Reorderable(reorder => reorder.Columns(true))
      .DataSource(dataSource => dataSource
          .Ajax()
          .PageSize(40)
          .Model(model =>
              {
                  model.Id(p => p.vessel_idx);
 
              })
          .Read(read => read.Action("vessels_Read", "BrokerHome"))
          .Update(update => update.Action("vessels_Update", "BrokerHome"))
      )
)

 

 

Thanks

Stefan
Telerik team
 answered on 10 Nov 2017
9 answers
1.9K+ views
Hi, i use kendo ui grid (for asp.net mvc)  without problem if i declare dataSource transport read as url like:

var dataSource = {
   pageSize: 20,
   batch: true,
   serverOperation: true,
   serverPaging: true,
   serverSorting: true,
   serverFiltering: true,
   type: "aspnetmvc-ajax",
   read:
   {
      url: '/Home/GetNodes',
      type: "POST",
      dataType: "json",
      data: function ()
      {
         return {'p1': 'some text', 'p2': 'other'}
      }
   }
};

now the problem is that i want do use function mode read (is a software design requirement)
but the sintax used to pass request parameters to server differ from use transport type "aspnetmvc-ajax" or not.
if i set transport type "aspnetmvc-ajax" the read function is not fired, 
but if not set transport type "aspnetmvc-ajax" the request parameter is not passed well on server side!

if i watch the post parameters sent via http:

with transport type "aspnetmvc-ajax":

page:1
pageSize:20
sort:Field1-asc
filter:Field1~eq~'value1'

without transport type "aspnetmvc-ajax":
page:1
pageSize:20
sort:[{field:Field1, dir:asc}]
filter:{filters:[{operator:eq, value:value1, field:Field1}], logic:and}

sort and filter value parameters differ from "aspnetmvc-ajax" version and server-side are null!

as workaround i manually parse the request params inside parameterMap as shown on bottom, 
translating sort and filter value sintax compliance with "aspnetmvc-ajax" version and server side are passed well.

- there is a best solution? 
- why if i use "aspnetmvc-ajax" transport type the read function is not invoked?
- if the only solution to use read function is to avoid using "aspnetmvc-ajax" transport type,
  there is a standard way to format request parameters for use on server side in DataSourceRequest object?

thanks

 attually my workaround is:

var dataSource = {
   pageSize: 20,
   batch: true,
   serverOperation: true,
   serverPaging: true,
   serverSorting: true,
   serverFiltering: true,
   read: function (options)
   {
      var request = $scope.grdDocuments.dataSource.transport.parameterMap({
          filter: $scope.grdDocuments.dataSource.filter(),
          group: $scope.grdDocuments.dataSource.group(),
          sort: $scope.grdDocuments.dataSource.sort(),
          page: $scope.grdDocuments.dataSource.page(),
          pageSize: $scope.grdDocuments.dataSource.pageSize()
      });
      
      httpService.GetNodes(request.filter, request.group, request.sort, request.page, request.pageSize, sFolderId, ... other parameters)
      .then(
      function (args)
      {
          //Verifica esito della richiesta http
          if (!sharedService.CheckHttpRequestResult(args, 'GetNodes'))
          {
              options.error(null);
              return;
          }

          options.success(args.data);
      }
      );
   },
   parameterMap: function (data, operation)
   {
      //Trasformazione parametro filter
      if (typeof data.filter !== 'undefined')
      {
         //normale: {filters:[{operator:eq, value:a, field:Affidatario}], logic:and}
         //trasformato: Affidatario~eq~'a'
         var filter = '';
         for (var i = 0; i < data.filter.filters.length; i++)
         {
            if (filter !== '')
               filter += '~' + data.filter.logic + '~';

            var fieldValue = "'" + data.filter.filters[i].value + "'";

            //Formattazione valore in base al formato della colonna
            var found = model.fields[data.filter.filters[i].field];
            if (typeof found !== 'undefined')
            {
               if (found.type === 'number')
                  fieldValue = data.filter.filters[i].value;
               else if (found.type === 'date')
                  fieldValue = "datetime'" + data.filter.filters[i].value.format('Y-m-d') + "T00-00-00'";
            }

            filter += data.filter.filters[i].field + '~' + data.filter.filters[i].operator + '~' + fieldValue;
         }
         data.filter = filter;
      }

      //Trasformazione parametro sort
      if (typeof data.sort !== 'undefined')
      {
         //normale: [{field:Anno, dir:asc}]
         //trasformato: Anno-asc
         var sort = '';
         for (var i = 0; i < data.sort.length; i++)
         {
            if (sort !== '')
               sort += '~';

            sort += data.sort[i].field + '-' + data.sort[i].dir;
         }
         data.sort = sort;
      }

      var result = JSON.parse(JSON.stringify(data));
      return result;
   }
};

server side:

public JsonResult GetNodes([DataSourceRequest]DataSourceRequest request, string sFolderId, ... other parameters)
{

}
Stefan
Telerik team
 answered on 10 Nov 2017
2 answers
757 views

I am trying to export grid to PDF and I want it to export all pages. In my grid I have 2 pages but pdf only shows first page. In the grid dataSource I have set ServerOperation(true) and what happens is that the read action is called 3 times, first time the request is marked page 1, second time the request is marked page 2 and then the third time the request is marked page 1 again and therefore it only exports the first page.

Here's my grid:

@(Html.Kendo().Grid<MembersViewModel>()
.Name("participantsGrid")
.Columns(columns =>
{
columns.Bound(c => c.ID).Visible(false);
columns.Template(@<text></text>).ClientTemplate(@"<div class=''>"
+ "# if (HasAllergies) { # <i id='al-#=ID#' class=\"fa fa-exclamation-circle allergies\" data-tooltiptext='#=Allergies#' aria-hidden=\"true\"></i> # } #"
+ "</div>").Width(20).HtmlAttributes(new
{
style = "padding-left:5px;padding-right:5px"
});
columns.Bound(c => c.NAME).Title(translator.Translate("NAME"));
columns.Bound(c => c.SSN).Title(translator.Translate("SSN"));
columns.Bound(c => c.GENDER).Title(translator.Translate("GENDER"));
columns.Bound(c => c.AGE).Title(translator.Translate("AGE"));
columns.Template(@<text></text>).ClientTemplate(@"<div class='dropdown'>"
+ "<a data-toggle='dropdown' class='primarycolor' href=''><i class='fa fa-ellipsis-v fa-2x'></i></a>"
+ "<ul class='dropdown-menu dm-icon pull-right'>"
+ "<li><a class='k-button-icontext k-grid-edit' href='" + Url.Action("Edit", "Members") + "/#=ID#'>" + translator.Translate("EDIT") + "</a></li>"
+ "<li><a class='k-button-icontext' href='##'>" + translator.Translate("REGISTER_CLASS") + "</a></li>"
+ "</ul>"
+ "</div>").HtmlAttributes(new
{
@class = "dropdown-gridcell"
}).Width(20);
})
.ToolBar(toolbar =>
{
toolbar.Template(@<text>
<a class="k-button k-button-icontext k-grid-add" href="@Url.Action("", "")"><i class="fa fa-plus" aria-hidden="true"></i> @translator.Translate("ADD") @translator.Translate("PARTICIPANT_TGF")</a>
<a class="k-button k-button-icontext k-grid-excel" href="#"><span class="k-button-icontext k-i-excel"></span>Excel</a>
<a class="k-button k-button-icontext k-grid-pdf" href="#"><span class="k-icon k-i-pdf"></span>PDF</a>
</text>);
toolbar.Excel();
toolbar.Pdf();
})
.Pdf(pdf => pdf
.AllPages()
.AvoidLinks()
.PaperSize("A4")
.Scale(0.8)
.Margin("2cm", "1cm", "1cm", "1cm")
.Landscape()
.RepeatHeaders()
.TemplateId("page-template")
.FileName(string.Format("{0}_{1}.pdf", User.Identity.GetOrgName().Replace(' ', '_'), translator.Translate("PARTICIPANTS_PDFNAME")))
.ProxyURL(Url.Action("Pdf_Export_Save", "PDF"))
)
.Groupable(g => g.Messages(m => m.Empty(translator.Translate("DRAG_DROP_TO_ZONE_GROUPING"))))
.Sortable()
.Pageable()
.Filterable(filterable => filterable
.Extra(false)
.Messages(m => m.Clear(translator.Translate("CLEAR")).Filter(translator.Translate("FILTER")))
.Operators(operators => operators
.ForString(str => str.Clear()
.Contains(translator.Translate("CONTAINS"))
.StartsWith(translator.Translate("STARTS_WITH"))
)
)
)
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(2)
.ServerOperation(true)
.Read(read => read.Action("Participants_Read", "Participants").Data("additionalData"))
.Model(model => model.Id(mid => mid.ID))
.Create(update => update.Action("Participants_Create", "Participants"))
)
)

 

Here's my template:

<script type="x/kendo-template" id="page-template">
    <div class="page-template">
        <div class="header">
            <div style="float: right">Page #: pageNum # of #: totalPages #</div>
        </div>
        <div class="watermark">SAVI VEFKERFI</div>
        <div class="footer">
            Page #: pageNum # of #: totalPages #
        </div>
    </div>
</script>

And here's my controller action:

public ActionResult Participants_Read([DataSourceRequest] DataSourceRequest request, int? did, int? sdid, int? cid, int? sid)
{
    List<MembersViewModel> list = memberRepository.GetParticipantMembersList(this.saviSite.OrgId, did, sdid, cid, sid);

    return Json(list.ToDataSourceResult(request));
}

 

Can you tell me what I'm doing wrong here? Thanks!

Jokull
Top achievements
Rank 1
 answered on 09 Nov 2017
1 answer
451 views

I'm just getting started with the grid, but I'm up to the point where I can load the grid with data from my database and I can call methods that I expect to use for Inserting and Updating records. Here's the markup for the view with the grid:

@using AdminAppII.Models
@model AdminAppII.Models.UsersCustomEditTemplate

@{
    ViewBag.Title = "Users";
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <div class="form-group">
            @Html.Label("Agency ID", new { @class = "control-label" })
            @Html.DropDownList("SelectedAgencyID", ViewBag.agencyList as SelectList, new { @class = "control-label" })
        </div>

        <div class="form-group">
            @(Html.Kendo().Grid<AdminAppII.Models.UsersCustomEditTemplate>()
                .Name( "Grid")
                .Columns( columns =>
                {
                    // TODO replace widths here with server-side call if we want to read in these values from a config file
                    columns.Bound(c => c.AgentID).Width(100);
                    columns.Bound(c => c.AgencyID).Width(100);
                    columns.Bound(c => c.Active).Width(100);
                    columns.Bound(c => c.FirstName).Width(150);
                    columns.Bound(c => c.MiddleName).Width(150);
                    columns.Bound(c => c.LastName).Width(150);
                    columns.Bound(c => c.EmployeeID).Width(100);
                    columns.Bound(c => c.Username).Width(150);
                    columns.Bound(c => c.Email).Width(200);
                    columns.Bound(c => c.Roles).Width(300);
                    columns.Bound(c => c.BMA2Active).Width(100);
                    columns.Bound(c => c.UseADAuthentication).Width(100);
                    columns.Bound(c => c.ADUserName).Width(100);

                    columns.Command(cmd => cmd.Edit()).Width(100);
                })
                .ToolBar(toolBar =>
                    {
                        toolBar.Create();
                    })
                .Pageable(pager => pager
                    .Input(true)
                )
                .Sortable()
                .Scrollable(s => s.Height(500)) //////////////////////// hard coded height
                .Filterable()
                .DataSource( dataSource => dataSource
                    .Ajax()
                    .Model( model => model.Id(m => m.DeptType))
                    .Read( read => read.Action("Read","Home"))
                    .PageSize(40) /////////////////////////////////////// hard coded items per page
                    .Update(up => up.Action("UpdateAgency", "Home"))
                    .Create(create => create.Action("CreateAgency", "Home"))
                )
                .Resizable(resize => resize.Columns(true))
                .Reorderable(reorder => reorder.Columns(true))
                .HtmlAttributes(new { style = "height: 550px" })  /// does control the height
                .Editable(ed => ed.Mode(GridEditMode.PopUp).TemplateName("UsersEditAdd"))
            )
        </div>
    </div>
    <div class="box wide">
        <a href="#" class="k-button" id="save" title="Saves changes like width and order. Need to click Load State to restore the changes.">Save State</a>
        <a href="#" class="k-button" id="load" title="Restores the state saved by the save state button.">Load State</a>
    </div>

<script type="text/javascript">
    var gridData;
    // want to replace 'select' with at variable that captures the ID of the drop down
    // and make sure it works
    // see https://stackoverflow.com/questions/23873302/add-click-event-on-an-option-in-html-select-tag for the event code
    $('select').change(function () {
        var agencyID = $(this).val().toString();
        location = '/Home/Users?refreshData=true&agencyID=' + agencyID;
    });
</script>
<script type="text/javascript">

    $(function () {
        var grid = $("#Grid").data("kendoGrid");

        $("#save").click(function (e) {
            e.preventDefault();
            localStorage["kendo-grid-options"] = kendo.stringify(grid.getOptions());
        });

        $("#load").click(function (e) {
            e.preventDefault();
            var options = localStorage["kendo-grid-options"];
            if (options) {
                grid.setOptions(JSON.parse(options));
            }
        });
    });
</script>

 

Here's the model:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace AdminAppII.Models
{
    public class UsersCustomEditTemplate
    {
        [Required]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Display(Name = "Middle Name")]
        public string MiddleName { get; set; }

        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Required]
        [Display(Name = "User Name")]
        public string Username { get; set; }

        [Display(Name = "Approval Email Address")]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }

        [Display(Name = "EZLabor Code")]
        public string EZLaborCode { get; set; }

        [Display(Name = "Official Name")]
        public string OfficialName { get; set; }

        [Display(Name = "Dept Type")]
        public string DeptType { get; set; }

        [Display(Name = "Comm Start Date")]
        [DataType(DataType.Date)]
        public DateTime? CommStartDate { get; set; }

        [Display(Name = "Agent Date Added")]
        [DataType(DataType.Date)]
        public DateTime? AgentDateAdded { get; set; }

        [Display(Name = "New Registration Note")]
        public string NewRegistrationNote { get; set; }


        [Display(Name = "License Number")]
        public string LicenseNumber { get; set; }

        [Display(Name = "Agent ID")]
        [Required]
        public int AgentID { get; set; }


        [Display(Name = "Agency ID")]
        [Required]
        public int AgencyID { get; set; }

        [Display(Name = "Employee ID")]
        public int? EmployeeID { get; set; }
        
        [Display(Name = "Active")]
        public int? Active { get; set; }

        [Display(Name = "BMA2Active")]
        public int? BMA2Active { get; set; }

        [Display(Name = "Use AD Authentication")]
        public int? UseADAuthentication { get; set; }

        [Display(Name = "AD User Name")]
        public string ADUserName { get; set; }

        [Display(Name = "Roles")]
        public string Roles { get; set; }

        //[Display(Name = "")]
        //public string  { get; set; }

    }
}

Here are the two methods in the Home controller mentioned in the grid to be called for the Create and Update

public ActionResult UpdateAgency([DataSourceRequest] DataSourceRequest dsRequest, UsersCustomEditTemplate agency)
        {
            if (agency != null && ModelState.IsValid)
            {
                // do update; this method is called for every line in the grid
            }
            
            return Json(ModelState.ToDataSourceResult());
        }
        public ActionResult CreateAgency([DataSourceRequest] DataSourceRequest dsRequest, UsersCustomEditTemplate agency)
        {
            if (agency != null && ModelState.IsValid)
            {
                // do update; this method is called for every line in the grid
            }

            return Json(ModelState.ToDataSourceResult());
        }

And, Here's the custom editor view:

 

@model AdminAppII.Models.UsersCustomEditTemplate
<div class="popupEditor">
    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.HiddenFor(model => model.AgencyID)
        @Html.HiddenFor(model => model.AgentID)

        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.MiddleName, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.MiddleName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.MiddleName, "", new { @class = "text-danger" })
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.EZLaborCode, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.EZLaborCode, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.EZLaborCode, "", new { @class = "text-danger" })
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.OfficialName, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.OfficialName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.OfficialName, "", new { @class = "text-danger" })
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.DeptType, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.DeptType, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DeptType, "", new { @class = "text-danger" })
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.CommStartDate, htmlAttributes: new { @class = "control-label" })
            @Html.Kendo().DateTimePickerFor(model => model.CommStartDate).HtmlAttributes(new {  @class = "form-control"})
            @Html.ValidationMessageFor(model => model.CommStartDate, "", new { @class = "text-danger" })
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.NewRegistrationNote, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.NewRegistrationNote, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.NewRegistrationNote, "", new { @class = "text-danger" })
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LicenseNumber, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.LicenseNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.LicenseNumber, "", new { @class = "text-danger" })
        </div>
    </div>
</div>

 

I've noticed that when I click the button to save the data I intend to Insert, both of the methods above in the controller are called. That surprised me. Why bother with two methods when both are called? Or, is there a way to make only one method is called depending on whether it's and Edit versus a Create?

More importantly, when these methods are called, they get called for every record in the grid. I just want the UpdateAgency method called once by the record being edited. And the CreateAgency method called once when the user submits the form that pops up from the toolbar.

Finally, and most important, I need to pass some values to the controller that are found in the data. I need to pass the AgencyID and AgentID to the controller when the CreateAgency method is called.

Thanks for any help,

Andy

 

Stefan
Telerik team
 answered on 09 Nov 2017
1 answer
863 views

Code -

 

@Html.Kendo().Grid(ViewBag.FSTableData as System.Data.DataTable).Name("RevGrid").Pageable().Sortable().Filterable().ToolBar(tools => tools.Excel()).Excel(excel => excel.FileName(@ViewBag.TableNameCleanExcel).AllPages(true)).DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
.PageSize(20)
.ServerOperation(false)
)

 

Hi there ,

 

I was woundering if it is possible to add an ID to the Export  To Excel button . What I need to do to if fire the button as soon as the pages loads . The grid we create are very dynamic and some user would just need the SpreadSheet downloaded .

 

Julian

Stefan
Telerik team
 answered on 09 Nov 2017
1 answer
669 views

I have a grid that uses a datatable as the mode. Here's the code for the grid:

@(Html.Kendo().Grid<dynamic>()
                .Name( "Grid")
                .Columns( columns =>
                {
                    foreach ( DataColumn col in Model.Columns)
                    {
                        var c = columns.Bound(col.ColumnName);
                        // handle special cases here, e.g. putting things in footer of grid
                        c.Width(200);
                    }
                    columns.Command(command => { command.Edit(); command.Destroy(); }).Width(250);
                })
                .ToolBar(toolbar => toolbar.Create())
                .Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("UsersEditAdd").Window(w => w.Title("Add or Edit User")))
                .Pageable(pager => pager
                    .Input(true)
                )
                .Sortable()
                .Scrollable(s => s.Height(500)) //////////////////////// hard coded height
                .Filterable()
                .DataSource( dataSource => dataSource
                    .Ajax()
                    .Model( model =>
                    {
                        // two lines below are in demo code. I get an index out of bounds from the next line
                        //var id = Model.PrimaryKey[0].ColumnName;
                        //model.Id(id);
                        model.Id("AgentID"); // this is required
                        foreach ( DataColumn col in Model.Columns)
                        {
                            var field = model.Field( col.ColumnName, col.DataType);
                        }
                    })
                    .Read( read => read.Action("Read","Home"))
                    .PageSize(40) /////////////////////////////////////// hard coded items per page
                    .Create(update => update.Action("EditingPopup_Create", "UsersGrid"))
                    .Update(update => update.Action("EditingPopup_Update", "UsersGrid"))
                    .Destroy(update => update.Action("EditingPopup_Destroy", "UsersGrid"))
                )
                .Resizable(resize => resize.Columns(true))
                .Reorderable(reorder => reorder.Columns(true))
                .HtmlAttributes(new { style = "height: 550px" })  /// does control the height
            )

 

The grid loads with data and an Edit button. When I click the Edit button, a screen pops up based on the columns and data in the grid row. But I want the edit button to bring up the view named UsersEditAdd. I created UsersEditAdd.cshtml in the same directory as the view with the grid.

I was looking at a similar posting, and it seems that I shold be seeing the view I created. But, no.

Any help would be appreciated.

Also, I'm currently using an evaluation version.

 

 

Viktor Tachev
Telerik team
 answered on 08 Nov 2017
3 answers
70 views

Hello,

Is there a way to use an overnight feature with Scheduler (week view)? I know that timeline views support such kind of setup, but unfortunately, I cannot archive the same behavior with the week view.

We use a week view scheduler without concrete dates. User sees a full week where he can adjust timeslots. Then we use this time slots to build series. Therefore, everything what was entered for one week will be extrapolated to all next weeks in the future. Everything is good, besides one case: overnight from Sat to Sun (week view starts from Sun and ends by Sat). By default, it creates an overnight slot for next Sun, but we need an overnight for the first Sun in the week (it looks like a cycle in context of one week).

Thanks, Dima.

Veselin Tsvetanov
Telerik team
 answered on 08 Nov 2017
1 answer
542 views

Hello,

I want to hide the CreateChild command ont he third level of my nodes.
So if wonder if a way to get the node level of an element exists on databound event ?

Or maybe ther is a better way to accomplish it ?

I started the databound event like this:

function dataBound(treeview) {
    var node;
    var nodes = treeview.sender.dataSource.view();
 
    for (var i = 0; i < nodes.length; i++) {
        node = nodes[i];
    }
}

I don't want use the hasChildren attribut beacause in my model sometimes element at level 2 doesn't have children.    

Thank you in advance

Stefan
Telerik team
 answered on 08 Nov 2017
2 answers
1.6K+ views

I'm using the Grid with ServerOperation disabled and PopUp editing. I wanted to use bootstrap style edit and delete buttons and a custom delete confirmation message, so I added a Template column with a ClientTemplate containing the buttons. The buttons have an onclick pointing at my javascript functions. The edit button is working successfully and calling the server action, but the delete button does not hit the server action. I've verified through Chrome Developer Tools that my javascript is being hit and it does execute the grid.removeRow(item); line without any errors, but after that nothing happens. The row remains in the grid and the delete action isn't hit (or called as far as I can tell from the Network tab.) What am I missing? 

 

    @(Html.Kendo().Grid<BirthdayAddOnEditVM>(Model.ViewModel.AddOns)
      .Name(Html.NameFor(m => m.ViewModel.AddOns).ToString())
      .DataSource(dataSource => dataSource
          .Ajax()
          .Model(model => { model.Id(p => p.ID); model.Field(p => p.ID).DefaultValue(Guid.Empty); })
          .PageSize(4)
          .ServerOperation(false)
          //.Read(read => read.Action("BirthdayItems_Read", "Birthdays"))
          .Create(create => create.Action("BirthdayItems_Save", "Birthdays"))
          .Update(update => update.Action("BirthdayItems_Save", "Birthdays"))
          .Destroy(destroy => destroy.Action("BirthdayItems_Delete", "Birthdays").Type(HttpVerbs.Post))
          .Events(events => events.Error("function(e){ gridError(e, '" + Html.IdFor(m => m.ViewModel.AddOns) + "'); }" ))
      )
      .Columns(columns =>
      {
          columns.Bound(c => c.Name).Title("Add-On");
          columns.Bound(c => c.Price).Format("{0:C}");
          columns.Bound(c => c.PublishOnWebsite).ClientTemplate("<input type=\"checkbox\" disabled #: (PublishOnWebsite ? 'checked' : '')# />");
          columns.Bound(c => c.AllowForOnlinePurchase).ClientTemplate("<input type=\"checkbox\" disabled #: (AllowForOnlinePurchase ? 'checked' : '')# />");
          columns.Command(command => { command.Edit().Text(""); command.Destroy(); }).Width(180);
          columns.Template(t => { }).HeaderTemplate("").ClientTemplate(@"
                            <button type='button' onclick='editGridRow(this)' class='btn btn-primary btn-xs'><span class='glyphicon glyphicon-pencil' title='Edit'></span></button>
                            <button type='button' onclick='deleteGridRow(this)' class='btn btn-danger btn-xs'><span class='glyphicon glyphicon-remove' title='Delete'></span></button>");
      })
      .ToolBar(toolbar =>
      {
          toolbar.Template(@<text>
                            <span class="col-sm">Add-Ons</span>
                            <span><button type="button" class="btn btn-primary btn-xs" onclick="createGridRow(this)" title="Add New"><span class="glyphicon glyphicon-plus"></span></button></span>
                    </text>);
                })
      .Editable(editable => editable.Mode(GridEditMode.PopUp).DisplayDeleteConfirmation(false))
      .Pageable()
      .Selectable(selectable =>
                  {
                      selectable.Mode(GridSelectionMode.Multiple);
                      selectable.Type(GridSelectionType.Row);
                  })
      .Sortable(sortable =>
                  {
                      sortable.SortMode(GridSortMode.SingleColumn);
                  })
      //.ColumnMenu()
      //.Navigatable()
      //.Filterable()
      //.Scrollable()
      .Deferred()
)

 

function editGridRow(elem) {
    var $elem = $(elem);
    var grid = $elem.closest("div[data-role='grid']").data("kendoGrid");
    var item = grid.dataItem($elem.closest("tr"))
 
    grid.editRow(item);
}
 
function deleteGridRow(elem){
    var $elem = $(elem);
    var grid = $elem.closest("div[data-role='grid']").data("kendoGrid");
    var item = grid.dataItem($elem.closest("tr"))
 
    if (confirm("Are you sure you want to delete " + item.Name + "?") === true)
        grid.removeRow(item);    //This gets hit
}
 public class BirthdaysController : Controller
{
    [HttpPost]
    public ActionResult BirthdayItems_Delete([DataSourceRequest]DataSourceRequest request, BirthdayAddOnEditVM birthdayItem)
    {
        //Never called
        ...
    }
}

 

As you may have noticed, I added the default edit and delete command buttons back in for testing. That delete button does call sever delete action. So I feel like grid.removeRow is not the right thing to use in my function, but that's what I've seen in all the examples. 

Jesse
Top achievements
Rank 1
Veteran
 answered on 07 Nov 2017
Narrow your results
Selected tags
Tags
Grid
General Discussions
Scheduler
DropDownList
Chart
Editor
TreeView
DatePicker
Upload
ComboBox
MultiSelect
ListView
Window
TabStrip
Menu
Installer and VS Extensions
Spreadsheet
AutoComplete
TreeList
Gantt
PanelBar
NumericTextBox
Filter
ToolTip
Map
Diagram
Button
PivotGrid
Form
ListBox
Splitter
Application
FileManager
Sortable
Calendar
View
MaskedTextBox
PDFViewer
TextBox
Toolbar
MultiColumnComboBox
Dialog
DropDownTree
Checkbox
Slider
Switch
Notification
ListView (Mobile)
Pager
Accessibility
ColorPicker
DateRangePicker
Wizard
Security
Styling
Chat
MediaPlayer
TileLayout
DateInput
Drawer
SplitView
Barcode
ButtonGroup (Mobile)
Drawer (Mobile)
ImageEditor
RadioGroup
Sparkline
Stepper
TabStrip (Mobile)
GridLayout
Template
Badge
LinearGauge
ModalView
ResponsivePanel
TextArea
Breadcrumb
ExpansionPanel
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
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Sergii
Top achievements
Rank 1
Iron
Iron
Dedalus
Top achievements
Rank 1
Iron
Iron
Lan
Top achievements
Rank 1
Iron
Doug
Top achievements
Rank 1
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Sergii
Top achievements
Rank 1
Iron
Iron
Dedalus
Top achievements
Rank 1
Iron
Iron
Lan
Top achievements
Rank 1
Iron
Doug
Top achievements
Rank 1
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?