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

Hi,

I have implemented a custom validation on the kendo grid. Ex: The column name is "DemandUnit" and value is "kVA"/"kW" or blank. The problem is if I change the value "kVA" to "kVAd" the validation message is showing but if I remove the "d" i.e. from "kVAd" to "kVA" the validation message not go away. I know kendo grid uses "MVVM" model but how I can force to apply validation always.

Here with code,

(function ($, kendo) {
        $.extend(true, kendo.ui.validator, {
            rules: { // custom rules               
                demandunitvalidation: function (input, params) {
                    if (input.is("[name='DemandUnit']") && input.val() != "") {
                        input.attr("data-demandunitvalidation-msg", "Demand unit must be kVA/kW or blank.");
                        return /^(kVA|kW)$/.test(input.val())
                    }
                    return true;
                },
            },
            messages: { //custom rules messages               
                demandunitvalidation: function (input) {
                    // return the message text
                    return input.attr("data-val-demandunitvalidation");
                }
            }
        });
    })(jQuery, kendo);

 

Any help will be appreicated.

Regards,

Ujjwal

Tsvetina
Telerik team
 answered on 10 Apr 2017
1 answer
590 views
I have a Kendo UI ASP.NET MVC grid with CRUD operations that is being submitted as part of a form. In the following snippet, I am trying to display a column with an inline editable combobox (bound to user names and IDs) that displays a user's name but has a value of the user's ID.

Submits form properly, but displays the user IDs rather than names:

columns.ForeignKey(p => p.UserId, (System.Collections.IEnumerable)ViewBag.Users, "SystemUserId", "Name").Title("User").EditorTemplateName("ComboBoxInForm").Visible(true).ClientTemplate("#= UserId #" +
"<input type='hidden' name='Users[#= index(data) #].UserId' value='#= UserId #' />"
);


ComboBoxInForm EditorTemplate:

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


If I remove the ClientTemplate that provides the form input tag, the user's name is what is displayed rather than the value of the user's ID which is what I want. However, I need to submit it in batch as a part of a form, so I cannot remove the form input tag.

Fails to submit the form (no input tag), but displays the user names rather than IDs correctly:

columns.ForeignKey(p => p.UserId, (System.Collections.IEnumerable)ViewBag.Users, "SystemUserId", "Name").Title("User").EditorTemplateName("ComboBoxInForm").Visible(true);


What solution can I use to combine these two requirements so that the grid column displays names (but with values of IDs) and also provides the form input tag?

Thanks.

Note: Cross-posted from here.

Boyan Dimitrov
Telerik team
 answered on 10 Apr 2017
1 answer
359 views

Hi,

I am encountering strange issue in kendo mvc grid. My kendo mvc grid supports two feature one is saving state which save the state of filter/column order in my local database and other one is to upload pdf files using link button in the row.

Now say I loaded my kendo mvc grid with some records and applied a date range filter on it and save the state of it. Now when i load that saved state and try to upload record I encounter following error on reloading grid after successful upload. Please check attached screenshot for more details :

Following are the details

kendo.cdn.telerik.com/2017.1.223/js/kendo.all.min.js:26 Uncaught Error: Cannot call method 'value' of kendoDropDownList before it is initialized at HTMLSelectElement.<anonymous> (https://kendo.cdn.telerik.com/2017.1.223/js/kendo.all.min.js:26:4132) at Function.each (https://kendo.cdn.telerik.com/2017.1.223/js/jquery.min.js:2:2881) at M.fn.init.each (https://kendo.cdn.telerik.com/2017.1.223/js/jquery.min.js:2:846) at M.fn.init.e.fn.(anonymous function) [as kendoDropDownList] (https://kendo.cdn.telerik.com/2017.1.223/js/kendo.all.min.js:26:4079) at init.refresh (https://kendo.cdn.telerik.com/2017.1.223/js/kendo.all.min.js:37:20463) at init.d (https://kendo.cdn.telerik.com/2017.1.223/js/jquery.min.js:2:3856) at init.trigger (https://kendo.cdn.telerik.com/2017.1.223/js/kendo.all.min.js:25:6794) at init._process (https://kendo.cdn.telerik.com/2017.1.223/js/kendo.all.min.js:28:3663) at init.success (https://kendo.cdn.telerik.com/2017.1.223/js/kendo.all.min.js:27:31463) at success (https://kendo.cdn.telerik.com/2017.1.223/js/kendo.all.min.js:27:30421)

Tsvetina
Telerik team
 answered on 10 Apr 2017
3 answers
934 views

I'm trying to write a declaration of a details grid as a ClientTemplate using an MVC wrapper with a ToClientTemplate() call. Within this grid I'm need to write another client template for a column with a conditional data binding expression.

I'm getting invalid template error:

Unhandled exception at line 3855, column 3 in http://localhost:1319/Scripts/jquery-3.1.1.js<br>0x800a139e - JavaScript runtime error: Invalid template:'<br><div class="k-widget k-grid" id="detail_#=BusinessEntityID#"><table><colgroup><col /></colgroup><thead class="k-grid-header"><tr><th class="k-header" data-field="EmailAddress1" data-index="0" data-title="Email Address1" scope="col"><span class="k-link">Email Address1</span></th></tr></thead><tbody><tr class="k-no-data"><td colspan="1"></td></tr></tbody></table></div><script><br> kendo.syncReady(function(){jQuery("\#detail_#=BusinessEntityID#").kendoGrid({"columns":[{"title":"Email Address1","headerAttributes":{"data-field":"EmailAddress1","data-title":"Email Address1"},"template":"# if(FirstName == \u0027John\u0027) { # \u003cspan\u003eJohns are great!\u003c/span\u003e # } else { # \u003cspan\u003e\\#=EmailAddress1\\#\u003c/span\u003e # } #","field":"EmailAddress1","encoded":true}],"scrollable":false,"messages":{"noRecords":"No records available."},"autoBind":false,"dataSource":{"type":(function(){if(kendo.data.transports['aspnetmvc-server']){return 'aspnetmvc-server';} else{throw new Error('The kendo.aspnetmvc.min.js script is not included.');}})(),"transport":{"read":{"url":""},"prefix":"detail_#=BusinessEntityID#-"},"serverPaging":true,"serverSorting":true,"serverFiltering":true,"serverGrouping":true,"serverAggregates":true,"filter":[],"schema":{"data":"Data","total":"Total","errors":"Errors","model":{"fields":{"BusinessEntityID":{"type":"number"},"EmailAddressID":{"type":"number"},"EmailAddress1":{"type":"string"},"rowguid":{"type":"string"},"ModifiedDate":{"type":"date"},"Person":{"type":"object"}}}}}});});<br><\/script><br><br><br>' Generated code:'var $kendoOutput, $kendoHtmlEncode = kendo.htmlEncode;with(data){$kendoOutput='\n<div class="k-widget k-grid" id="detail_'+(BusinessEntityID)+'"><table><colgroup><col /></colgroup><thead class="k-grid-header"><tr><th class="k-header" data-field="EmailAddress1" data-index="0" data-title="Email Address1" scope="col"><span class="k-link">Email Address1</span></th></tr></thead><tbody><tr class="k-no-data"><td colspan="1"></td></tr></tbody></table></div><script>\n\tkendo.syncReady(function(){jQuery("#detail_'+(BusinessEntityID)+'").kendoGrid({"columns":[{"title":"Email Address1","headerAttributes":{"data-field":"EmailAddress1","data-title":"Email Address1"},"template":"'; if(FirstName == \u0027John\u0027) { ;$kendoOutput+=' \u003cspan\u003eJohns are great!\u003c/span\u003e '; } else { ;$kendoOutput+=' \u003cspan\u003e\#=EmailAddress1\#\u003c/span\u003e '; } ;$kendoOutput+='","field":"EmailAddress1","encoded":true}],"scrollable":false,"messages":{"noRecords":"No records available."},"autoBind":false,"dataSource":{"type":(function(){if(kendo.data.transports[\'aspnetmvc-server\']){return \'aspnetmvc-server\';} else{throw new Error(\'The kendo.aspnetmvc.min.js script is not included.\');}})(),"transport":{"read":{"url":""},"prefix":"detail_'+(BusinessEntityID)+'-"},"serverPaging":true,"serverSorting":true,"serverFiltering":true,"serverGrouping":true,"serverAggregates":true,"filter":[],"schema":{"data":"Data","total":"Total","errors":"Errors","model":{"fields":{"BusinessEntityID":{"type":"number"},"EmailAddressID":{"type":"number"},"EmailAddress1":{"type":"string"},"rowguid":{"type":"string"},"ModifiedDate":{"type":"date"},"Person":{"type":"object"}}}}}});});\n<\/script>\n\n';}return $kendoOutput;'

 

looks like the problem is the conditional expression in the if statement:

    if(FirstName == \u0027John\u0027)

the single quote is encoded. What do I have to do to prevent that? Is there a way to escape single quote?

Here is sample code:

@(
    Html.Kendo().Grid<Person>().Name("parentGrid")
    .Columns(col =>
    {
        col.Bound(per => per.FirstName);
        col.Bound(per => per.LastName);
        col.Bound(per => per.ModifiedDate);
    })
    .DataSource(ds => ds.Ajax().Read("GetPeople", "DetailGrid"))
    .ClientDetailTemplateId("tmpl")
)
 
<script id="tmpl" type="text/x-kendo-template">
@(
    Html.Kendo().Grid<EmailAddress>().Name("detail_#=BusinessEntityID#")
     .Columns(col =>
     {
         col.Bound(e => e.EmailAddress1)
         .ClientTemplate("# if(FirstName == 'John') { # <span>Johns are great!</span> # } else { # <span>\\#=EmailAddress1\\#</span> # } #");
     })
     .ToClientTemplate()
)
</script>
Nikita
Top achievements
Rank 2
Iron
 answered on 07 Apr 2017
2 answers
115 views

Hello,

I'm using visualTemplate to see from my model (dataItem) whether entity is of one type or the other to use, among other things, corresponding image for the entity.

I'm also using (Editable) Tools under ShapeDefaults to have some custom tools for the entities in the model.

Now, I would like that depending on the entity type from the model I can choose which custom tool will be shown to the user. How can I do this?

 

For more clarity, mvc razor part:

.ShapeDefaults(sd => sd
     .Visual("visualTemplate")
     .Editable(e => e
          .Tools(t =>
           {
                 t.Custom().Name("firstTypeCustomButton");
                 t.Custom().Name("secondTypeCustomButton")
           }
...

 

Javascript template:

function visualTemplate(options) {

...

    if ( options.dataItem.EntityType == "myFirstType") {
         group.append(new dataviz.diagram.Image({
                    source: "@Url.Content("~/Images/first-type-image.png")",
...
    else if ( options.dataItem.EntityType == "mySecondType") {
...
Zoltan
Top achievements
Rank 1
 answered on 07 Apr 2017
1 answer
516 views

I have the following code in an MVC page. When I export to PDF, the content in the "page-template" script tag prints at the bottom of the grid on each page instead of the top, as I thought it should because I've specified a class type of "header".

 

<script type="x/kendo-template" id="page-template">
    <div class="page-template">
        <div class="header">
            <div style="float: right">Page #: pageNum # of #: totalPages #</div>
            Multi-page grid with automatic page breaking
        </div>
    </div>
</script>

<div id="main-content" class="JeffreysContainer">
    <h3 class="text-center">Dealer Closeout History</h3>

    @(Html.Kendo().Grid<JeffreysOnline.Entities.vwCloseout>()
            .Name("grid")
            .Columns(columns =>
            {
                columns.Bound(p => p.CloseoutDate).Width(120).Format("{0:MM/dd/yyyy}");
                columns.Bound(p => p.BeginDate).Width(120).Format("{0:MM/dd/yyyy}");
                columns.Bound(p => p.EndDate).Width(120).Format("{0:MM/dd/yyyy}");
                columns.Bound(p => p.BoothNumber).Title("Booth").Width(80);
                columns.Bound(p => p.DealerName).Title("Dealer Name").Width(100);
                columns.Bound(p => p.DealerId).Title("Dealer Id").Width(100);
                columns.Bound(p => p.RetailSales).Width(125);
                columns.Bound(p => p.WholesaleSales).Width(125);
                columns.Bound(p => p.LayawayPayments).Title("Deposit Payments").Width(125);
                columns.Bound(p => p.RentWithheld).Title("Rent").Width(125);
                columns.Bound(p => p.CommissionWithheld).Title("Commissions").Width(125);
                columns.Bound(p => p.ChargeCardFees).Title("Charge Fees").Width(125);
                columns.Bound(p => p.AssessmentWithheld).Title("Asessment").Width(125);
                columns.Bound(p => p.TotalPayout).Title("Total Payout").Width(125);
                columns.Bound(p => p.CheckNumber).Title("Check Number").Width(125);
            })
            .ToolBar(toolbar =>
            {
                toolbar.Excel();
                toolbar.Pdf();
            })
            .ColumnMenu()
            .Excel(excel => excel
                .FileName("CloseoutHistory.xlsx")
                .Filterable(true)
                .AllPages(true)
                .ProxyURL(Url.Action("ExcelExport", "Customer"))
             )
             .Pdf(pdf => pdf
                .AllPages()
                .AvoidLinks()
                .PaperSize("A4")
                .Scale(0.6)
                .Margin("2cm", "1cm", "1cm", "1cm")
                .Landscape()
                .RepeatHeaders()
                .Title("Closeout History")
                .TemplateId("page-template")
                .FileName("CloseoutHistory.pdf")
                .ProxyURL(Url.Action("PdfExport", "Dealer"))
            )
             .DataSource(dataSource => dataSource
                .Ajax()
                .Batch(false)                                               // We want to perform batch operations
                .PageSize(50)                                               // Set the page size
                .Events(events => events.Error("gridErrorHandler"))         // Define a function that gets called on an error
                .Read(read => read.Action("ReadCloseoutHistory", "Closeout"))  // The Read method in the controller
             )
    )
</div>

Stefan
Telerik team
 answered on 07 Apr 2017
19 answers
711 views
Hi there,

I'm using a custom filter for different data types. Actually, this works pretty well as long as I use 'en-US' as culture and I don't switch to another. The possibility of changing the culture is part of my application. When changing the culture to e.g. 'de-DE', the standard grid filter is displayed instead of my custom one. Switching back to 'en-US', everything works again like it should.

Below an example for one my grids and also how I change the culture in my application.

@(Html.Kendo().Grid(Model)
      .Name("FolderIndexGrid")
      .Pageable(e => e.PageSizes(new int[] {10, 20, 40, 80, 100}))
      .Sortable()
      .Filterable(f => f
          .Operators(g =>
              g.ForString(h =>
                {
                  h.Clear();
                  h.Contains(Resources.Resource.Contains);
                  h.DoesNotContain(Resources.Resource.DoesNotContain);
              })))
      .Scrollable(s => s.Height("auto"))
      .HtmlAttributes(new {@class = "maxHeight"})
      .RowAction(e =>
            {
                if (e.DataItem.Deleted)
                {
                    e.HtmlAttributes["style"] = "background-color:red;";
                }
            })
      .Columns(column =>
          {
              column.Bound(o => o.FileNr).Width(200).Title(Resources.FieldResource.FileNr)
                         .ClientTemplate(
                            
"<a href='" + Url.Action("Overview", "FileOverview") + "/#= FileNr #'" + ">#=FileNr#</a>"
                         );
              column.Bound(o => o.LovManufacturerId).Width(150).Title(Resources.FieldResource.LovManufacturerId);
              column.Bound(o => o.Name).Width(200).Title(Resources.FieldResource.FileName);
              column.Bound(o => o.Description);
              column.Template(@<text></text>).Title(Resources.FieldResource.Actions).Width(90)
                    .ClientTemplate(
                    "<a href=" + Url.Action("Overview", "FileOverview") + "/#= FileNr #" + ">
                               <img src=\"../../Content/images/zoom.png\" />
                           </a>"
+
                    "<a style=\"margin: 5px;\" href=" + Url.Action("Edit", "File") + "/#= FileNr #" + ">
                               <img src=\"../../Content/images/pencil.png\" />
                           </a>"
);
           }
      )
          .DataSource(dataSource => dataSource
                   .Ajax()
                   .Read(read => read.Action("Folder_Read", "Fetch", new { engineId = ViewBag.EngineId}))
                   .PageSize(40)
                   .Sort(sort => sort.Add("FileNr").Ascending()
          ))
          .ClientDetailTemplateId("detailview")
)

Changing the culture in _Layout.cshtml:
@{
    var culture = System.Threading.Thread.CurrentThread.CurrentCulture;
}
<script src="@Url.Content("~/Scripts/kendo/2014.1.528/cultures/kendo.culture." + culture + ".min.js")"></script>
<script>
    kendo.culture("@culture");
</script>

Best regards,
Jürgen

Viktor Tachev
Telerik team
 answered on 07 Apr 2017
1 answer
174 views

Hey out there,

currently we try to switch our Grid (old Telerik Grid)  and its functionality to the Kendo Grid.. Everythings works pretty fine except PDF export.

https://pastebin.com/z5AG95hx 

This snippet demonstrates the way the grid is embedded. Excel Export works fine. PDF Export returns empty pdf file. If I force proxy I get the following error:

n caught TypeError: t.split is not a function

    at n (kendo.all.js:3292)

If I don't use a proxy I get an empty file and no action seems to get called.

Whats the secret? Thanks in advance..

 

 

Stefan
Telerik team
 answered on 07 Apr 2017
1 answer
1.0K+ views

Hello,

I use the following MVC Grid with AutoGenerate columns because we use a query builder and the result are always different resultsets with different columns...

the Problem with that solution is the Format for specific columns like date, datetime and boolean, because they are not formatted the right way

is there a possibility to format specific columns if to use AutoGenerate columns?

 

@(Html.Kendo().Grid<dynamic>()
      .Name("gridEQ")
      .Columns(columns => columns.AutoGenerate(true))
      .Pageable()
      .Sortable()
      .Scrollable(s => s.Height("auto"))
      .NoRecords()
      .Filterable(f => f.Enabled(false))
      .AutoBind(false)
      .DataSource(dataSource => dataSource
          .Ajax()
          .PageSize(100)
          .Read(read => read.Action("ReadAsync", "Home").Data("GetQuerySQL"))
          .Events(e => e.Error("gridError"))
      )
)
Tsvetina
Telerik team
 answered on 06 Apr 2017
5 answers
313 views

When I pull up my map (Center is on Michigan) and scroll in or out with my mouse, the map centers on Africa and starts scrolling in or out from there.  It doesn't matter where the map is, scrolling with the mouse always moves the map over to Africa.  How do I fix that so that the map scrolls in or out, based on where the mouse pointer is?

Here is my cshtml razor object:

@(Html.Kendo().Map()
      .Name("crimemapping_results")
      .Center(Model.DefaultLatitude, Model.DefaultLongitude)
      .Zoom(3)
      .MinZoom(3)
      .Wraparound(true)
      .Layers(layers =>
      {
          layers.Add()
              .Type(MapLayerType.Tile)
              .UrlTemplate("http://#= subdomain #.tile.openstreetmap.org/#= zoom #/#= x #/#= y #.png")
              .Subdomains("a", "b", "c")
              .Attribution("© <a href='http://osm.org/copyright'>OpenStreetMap contributors</a>");
 
          layers.Add().AutoBind(false)
              .Type(MapLayerType.Bubble)
              .Style(style => style
                  .Fill(fill => fill.Color("#00f").Opacity(0.4))
                  .Stroke(stroke => stroke.Width(0))
              )
              .DataSource(dataSource => dataSource
                  .Read(read => read.Action("CrimeMapping_Map", "Home").Data("map_get"))
              )
              .LocationField("latlng")
              .ValueField("DataCount");
      })
      .Events(events => events
          .ShapeMouseEnter("onShapeMouseEnter")
          .Reset("onReset")
      )
)
Alex Hajigeorgieva
Telerik team
 answered on 06 Apr 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?