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

I'm creating a dashboard. The backend database stores the type of telerik chart control should go into which box. Very simply is it even possible based on the data response to then add that telerik chart control to the corresponding div? Sample code below.

Anytime I attempt this there are javascript errors due to the HTML and javascript emitted from the toHtmlString() method.
However I see no other way to perform this based on the javascript setup.

At this point it's 100% static to determine if this is even feasible.

<script>
//pseudo code to get data from database
//now add the right control to the div

 switch(controlType) {
            case "grid":
                break;
            case "bar":
                break;
            case "pie":
                $('#widgetcontrol' + widgetId).html('@(Html.Kendo().Chart()
                  .Name("pieChart")
                  .Legend(legend => legend
                      .Position(ChartLegendPosition.Top)
                  )
                  .ChartArea(chartArea => chartArea
                      .Background("transparent")
                      .Height(250)
                  )
                  .Series(series =>
                  {
                      series.Pie(new dynamic[]
                      {
                          new {category = "Test", value = 957, color = "#9de219"},
                          new {category = "Test 2", value = 124, color = "#90cc38"},
                          new {category = "Test 3", value = 567, color = "#068c35"},
                          new {category = "Test 4", value = 678, color = "#006634"},
                    })
                        .Labels(labels => labels
                          .Template("#= category #: \n #= value# (#= kendo.format('{0:P}', percentage)#)")
                          .Background("transparent")
                          .Visible(false)
                        )
                        .StartAngle(150);
                    })
                    .Tooltip(tooltip => tooltip
                       .Visible(true)
                       .Template("#= category #: \n #= value# (#= kendo.format('{0:P}', percentage)#)")
                    ).ToHtmlString())');
                break;
            case "counter":
                break;

Stefan
Telerik team
 answered on 10 Nov 2017
1 answer
623 views

I have this property :

public string Commax_dosismaximam2 = "0,03"

 

And when it renders on the grid it become to 3.

I know is something about the culture because if I change it to "0.03" works fine, but the thing is I made it string to avoid this, I donĀ“t understand why kendo have to convert a string to a int. 

 

Thank you

Konstantin Dikov
Telerik team
 answered on 10 Nov 2017
6 answers
190 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.3K+ 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.8K+ 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
746 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
448 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
848 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
652 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
67 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
Narrow your results
Selected tags
Tags
+? more
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?