Telerik Forums
UI for ASP.NET AJAX Forum
4 answers
263 views

As for the context:
We're using telerik:RadEditor to e.g. edit and display html-contents including SVGs (scalable vector graphics). In this editor we have declared multiple EditorContextMenu containing EditorTools, which call custom js-functions which in turn perform the intended actions.

This is an extract of our code:

<script type="text/javascript">
    Telerik.Web.UI.Editor.CommandList["ChangeDiagramm"] = function (commandName, editor, args) {
        var elem = editor.getSelectedElement();
        /* Issue: Depending on the browser, "elem" is or is not a SVG, although the EditorContextMenu, mentioned below, is the only one calling this js-function! */
        if (elem.tagName.toUpperCase() == "SVG") {
            StartModalDialog('EditHtmliagramRedirect.aspx?ID=' + elem.attributes.name.value, 500, 600, 1);
        }
    };
</script>

<telerik:RadEditor ExternalDialogsPath="~/Documentation/Documentation/Dialogs/Editor/Controls" EnableTrackChanges="false" 
    EnableComments="false" ID="ReHtml" EnableResize="False" NewLineMode="P" runat="server" OnClientLoad="OnClientLoaded" 
    OnClientSubmit="OnClientSubmit" OnClientPasteHtml="OnClientPasteHtml" OnClientCommandExecuting="OnClientCommandExecuting" 
    OnClientCommandExecuted="OnClientCommandExecuted" OnClientSelectionChange="OnClientSelectionChanged" UseRadContextMenu="False">

    <ContextMenus>
        <telerik:EditorContextMenu TagName="svg">
            <telerik:EditorTool Name="ChangeDiagramm" ShowIcon="true" Text="Edit SVG" ShowText="false" />
        </telerik:EditorContextMenu>
        <%--                         
		More EditorContextMenus each of which for different html-tags; none of them related to SVGs (img, a, li, span, ...)
        --%>
    </ContextMenus>
    
</telerik:RadEditor>

 

Example-editor-content:

<p>before</p><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="391px" height="221px" viewBox="-0.5 -0.5 391 221" name="c26facdc-b9af-46d3-8de6-7afc86696afa"><defs style=""></defs><g style=""><rect x="0" y="0" width="80" height="80" fill="#ffffff" stroke="#000000" pointer-events="all"></rect>
<path d="M 110 0 L 210 0 L 230 40 L 210 80 L 110 80 L 130 40 Z" fill="#ffffff" stroke="#000000" stroke-miterlimit="10" pointer-events="all"></path>
<path d="M 270 0 L 370 0 L 390 20 L 390 80 L 290 80 L 270 60 L 270 0 Z" fill="#ffffff" stroke="#000000" stroke-miterlimit="10" pointer-events="all"></path>
<path d="M 270 0 L 370 0 L 390 20 L 290 20 Z" fill-opacity="0.05" fill="#000000" stroke="none" pointer-events="all"></path>
<path d="M 270 0 L 290 20 L 290 80 L 270 60 Z" fill-opacity="0.1" fill="#000000" stroke="none" pointer-events="all"></path>
<path d="M 290 80 L 290 20 L 270 0 M 290 20 L 390 20" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="all"></path>
<path d="M 40 80 Q 80 220 205 220 Q 330 220 339.55 86.35" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke"></path>
<path d="M 339.92 81.12 L 342.91 88.35 L 339.55 86.35 L 335.93 87.85 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all"></path>
</g></svg><p>after</p>

For a long time, this code was working as intended in Firefox, Chrome and Microsoft Edge (the new one, based on the chromium engine). I.e. if someone right-clicks the svg-graphic in "Design"-mode of the editor, the corresponding js-function is being called and the "elem"-variable within the js-function has been set to the svg-element of the "Example-editor-content", hence fulfilling the if-statement and opening the modal dialog.

As of recent Edge and Chrome now show "elem" to be the "p"-tag containing the text "after", whereas Firefox still works as intended and sets "elem" to the "svg"-tag. Unfortunately I don't know the exact date, when it broke.

I suspect, the issue might be due to changes in Chrome/Edge/chromium, because the same issue also arises in older versions of our web-application. But since the editor.getSelectedElement-js-function is a black-box to me, I'm not able to confirm this.

Could you please investigate this issue?

Matthias
Top achievements
Rank 2
Iron
 answered on 07 Apr 2022
1 answer
515 views

Does anyone know what the CSP (Content-Security-Policy) be implemented for both HTTP and HTTPS when using Bing for the MapLayer control?

This is what I have, which breaks the map feature:

     <meta http-equiv="Content-Security-Policy"
    content="script-src 'self' 'unsafe-inline' 'unsafe-eval' https://aspnet-scripts.telerikstatic.com ;
             style-src 'self' 'unsafe-inline' https://aspnet-skins.telerikstatic.com ;
             font-src 'self' https://aspnet-skins.telerikstatic.com ;
             img-src 'self' https://aspnet-skins.telerikstatic.com " />

The error is: 

Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScripts_=%3b%3bSystem.Web.Extensions%2c+Version%3d4.0.0.0%2c+Culture%3dneutral%2c+PublicKeyToken...yada yada yada.. Refused to load the script 'http://dev.virtualearth.net/REST/v1/Imagery/Metadata/road?output=json&jsonp=bingTileParams&include=ImageryProviders&key=my key&callback=bingTileParams&_=1649186230772' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://aspnet-scripts.telerikstatic.com". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

I'm new to having to use CSP so I could really use your help.

Rumen
Telerik team
 answered on 06 Apr 2022
1 answer
177 views
Hello Support team,

We are facing some issues while adding list items in RadEditor, if the default size is changed it changes the size of the text in the list item but it does not change the size of the numbers representing each list item.
can you please check the attached screenshot?

Please look into it and let us know if you need any other information.

Thanks & Regards
Rumen
Telerik team
 answered on 06 Apr 2022
1 answer
146 views
Hi,
  we are using radhtml chart, in that we bind Y axis, Y axis and color for each bars, in that we want to rotate the XAxis bar value horizontal to vertical, here i attach screenshot of current and what we want, is there any properties to change this? i am not asking for LabelsAppearance or legend text.

Note: Chart we create dynamically and bind data.


Thanks
Vessy
Telerik team
 answered on 05 Apr 2022
0 answers
62 views

Hi Team,

We are having issue with yahoo interface after telerik upgrade.


protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);



RegisterIncludes();

_triggerLink.Text = Text;



if(!string.IsNullOrEmpty(MenuBodyId))
_menuPanel.Attributes.Add("menu-body", MenuBodyId);



var attributes = new List<string> {string.Format("clicktohide:{0}", ClickToHide.ToString().ToLower())};



_attributes.Text = string.Empty;
_attributes.Text += string.Join("|", attributes.ToArray());



_targets.Text = string.Empty;
if(Links != null && Links.Count() > 0)
_targets.Text = string.Join("|", Links.ToArray());
}



private void RegisterIncludes()
{
RegisterJs("utils", "~/include_common/YUI/test.js");
RegisterJs("container_core", "~/common/YUI/core-min.js");
RegisterJs("menu_min", "~/common/YUI/testmenu-min.js");
}



private void RegisterJs(string key, string relativeUrl)
{
if(!Page.ClientScript.IsClientScriptIncludeRegistered(key))
Page.ClientScript.RegisterClientScriptInclude(key, ResolveUrl(relativeUrl));
}

Can anyone help me out to resolve this issue
Sachita
Top achievements
Rank 1
Iron
Iron
Iron
 asked on 05 Apr 2022
1 answer
86 views

I have a web application that dynamically builds its rows and columns.  The data type is specified for each row in column 2.  As you see in the ASPX code below, I use the OnKeyPress client-side event to try to prevent letters from being entered into numeric fields (R for real, and I for integer).

ASPX:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <telerik:RadStyleSheetManager ID="RadStyleSheetManager1" runat="server" />
</head>
<body>
    <form id="form1" runat="server">
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
            <Scripts>
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
            </Scripts>
        </telerik:RadScriptManager>
        <script type="text/javascript">

            function OnGridCreated(sender, args) {
                // Resize columns to fit data
                var grid = sender;
                var gridElement = grid.get_element();

                // Attach the keydown event
                $telerik.$(gridElement).on('keydown', OnKeyDown);

                var masterTable = grid.get_masterTableView();
                var columns = masterTable.get_columns();

                // Resize all Columns
                columns.forEach(col => col.resizeToFit());

                // Collect the width of all columns
                var allColumnsWidth = columns.map(col => col.get_element().offsetWidth);

                // Get the Frozen Scroll
                var frozenScroll = $telerik.$(gridElement).find('div[id$=_Frozen]').get(0);
                var scrollLeftOffset = 0;
                var lastWidth = 0;

                // Assign function to recalculate scrolling
                $telerik.$(grid.GridDataDiv).on('scroll', function (e) {
                    for (var i = 0; i < columns.length; i++) {
                        if (!columns[i].get_visible()) {
                            scrollLeftOffset += allColumnsWidth[i];
                            lastWidth = allColumnsWidth[i];
                        }
                    }
                    var thisScrollLeft = this.scrollLeft;
                    this.scrollLeft = 0;
                    if (thisScrollLeft > 0) {
                        // To insure the current cell is not on the right edge, add the last column's width
                        frozenScroll.scrollLeft = thisScrollLeft + scrollLeftOffset + lastWidth;
                    }
                    scrollLeftOffset = 0;
                })
            }

            function OnKeyDown(event) {
                // Look for TAB
                if (event.which == 9) {
                    var gridElement = event.currentTarget;
                    var grid = gridElement.control;
                    var masterTableView = grid.get_masterTableView();
                    var target = event.target;
                    var currentCell = $telerik.$(target).closest('td.rgBatchCurrent').get(0);

                    if (!currentCell) return;
                    var cellIndex = currentCell.cellIndex;
                    var numColumns = masterTableView.get_columns().length - 1;

                    var frozenScroll = $telerik.$(gridElement).find('div[id$=_Frozen]').get(0);

                    if (!event.shiftKey) {
                        if (cellIndex == numColumns) {
                            // Reset scroll position to left edge
                            frozenScroll.scrollLeft = 0;
                        }
                    }
                    else {
                        // Reduce the scroll position by the current cell's width
                        frozenScroll.scrollLeft = frozenScroll.scrollLeft - currentCell.offsetWidth;
                    }
                }
            }

            function OnKeyPress(sender, args)
            {
                // What is the key that was pressed
                var c = args.get_keyCode();

                // What is this row's data type (second column)
                var d = args._domEvent.rawEvent.path[3].cells[1].textContent.trim();

                var isNumeric = (c >= 48 && c <= 57);  // 0 through 9
                var isNegative = (c == 45);  // hyphen or minus
                var isSymbol = (c == 44) || (c == 46);  // comma or period
                var isModifier = (args._isAltPressed || args._isCtrlPressed || args._isShiftPressed);

                console.log(c);
                console.log(d);
                console.log(isNumeric);
                console.log(isNegative);
                console.log(isSymbol);
                console.log(isModifier);

                if (d == 'S') {
                    // string allows everything
                    args.set_cancel(false);
                } else if (d == 'I') {
                    // integer allows numbers and minus
                    var xxx = !((isNumeric || isNegative) && !isSymbol && !isModifier);
                    console.log(xxx)
                    args.set_cancel(xxx);
                } else if (d == 'R') {
                    var xxx = !((isNumeric || isNegative || isSymbol) && !isModifier);
                    console.log(xxx)
                    // real allows numbers, minus, comma, and decimal
                    args.set_cancel(xxx);
                }
                
            }

        </script>
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
        </telerik:RadAjaxManager>
        <div>
            <telerik:RadGrid ID="RadGrid1" runat="server"
                OnNeedDataSource="RadGrid1_NeedDataSource"
                AutoGenerateColumns="False">
                <ClientSettings AllowKeyboardNavigation="True">
                    <Scrolling FrozenColumnsCount="2" AllowScroll="True" ScrollHeight="600px" UseStaticHeaders="True"></Scrolling>
                    <Selecting CellSelectionMode="None" AllowRowSelect="True"></Selecting>
                    <ClientEvents OnGridCreated="OnGridCreated" OnKeyPress="OnKeyPress" />
                    <Resizing AllowColumnResize="True" AllowResizeToFit="True" ClipCellContentOnResize="False" />
                </ClientSettings>
                <AlternatingItemStyle Wrap="True" BackColor="Gainsboro"></AlternatingItemStyle>
                <MasterTableView CommandItemDisplay="TopAndBottom" DataKeyNames="PeopleID" EditMode="Batch" TableLayout="Fixed">
                    <BatchEditingSettings EditType="Row" />
                    <Columns>
                    </Columns>
                    <CommandItemSettings ShowAddNewRecordButton="False" />
                </MasterTableView>

                <HeaderStyle VerticalAlign="Bottom" Font-Bold="True" BackColor="DarkSeaGreen" Wrap="False"></HeaderStyle>

                <ActiveItemStyle Wrap="True"></ActiveItemStyle>

            </telerik:RadGrid>
        </div>
    </form>
</body>
</html>

 

C#:

using System;
using Telerik.Web.UI;
using System.Data;

public partial class Default : System.Web.UI.Page
{
    protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        DataTable dt = new DataTable();
        DataRow dr;
        int rowsNum = 130;
        string[][] colsInfo = {
        new string[] { "PeopleID", "number" },
        new string[] { "Type", "string" },
        new string[] { "Custom1", "string" },
        new string[] { "Custom2", "string" },
        new string[] { "Custom3", "string" },
        new string[] { "Custom4", "string" },
        new string[] { "Custom5", "string" },
        new string[] { "Custom6", "string" },
        new string[] { "Custom7", "string" },
        new string[] { "Custom8", "string" },
        new string[] { "Custom9", "string" },
        new string[] { "Custom10", "string" },
        new string[] { "Custom11", "string" },
        new string[] { "Custom12", "string" },
        new string[] { "Custom13", "string" },
        new string[] { "Custom14", "string" },
        new string[] { "Custom15", "string" },
        new string[] { "Custom16", "string" },
        new string[] { "Custom17", "string" },
        new string[] { "Custom18", "string" },
        new string[] { "Custom19", "string" },
        new string[] { "Custom20", "string" },
    };

        for (int i = 0; i < colsInfo.Length; i++)
        {
            GridBoundColumn newColumn = new GridBoundColumn();
            newColumn.DataField = colsInfo[i][0];
            newColumn.UniqueName = colsInfo[i][0];
            newColumn.HeaderText = "*" + colsInfo[i][0] + "*";
            RadGrid1.MasterTableView.Columns.Add(newColumn);

            switch (colsInfo[i][1])
            {
                case "string":
                    dt.Columns.Add(new DataColumn(colsInfo[i][0], typeof(String)));
                    break;
                case "number":
                    dt.Columns.Add(new DataColumn(colsInfo[i][0], typeof(Int32)));
                    break;
                case "date":
                    dt.Columns.Add(new DataColumn(colsInfo[i][0], typeof(DateTime)));
                    break;
                case "bool":
                    dt.Columns.Add(new DataColumn(colsInfo[i][0], typeof(Boolean)));
                    break;
                default:
                    break;
            }
        }

        for (int j = 1; j <= rowsNum; j++)
        {
            dr = dt.NewRow();

            for (int k = 0; k < colsInfo.Length; k++)
            {
                switch (colsInfo[k][1])
                {
                    case "string":
                        string x = "";
                        if (k == 1)
                        {
                            if ((j % 3) == 0)
                                x = "S";
                            else if ((j % 2) == 0)
                                x = "I";
                            else
                                x = "R";
                        }
                        dr[colsInfo[k][0]] = x;
                        break;
                    case "number":
                        dr[colsInfo[k][0]] = j;
                        break;
                    case "date":
                        dr[colsInfo[k][0]] = DateTime.Now;
                        break;
                    case "bool":
                        dr[colsInfo[k][0]] = j % 2 == 1 ? true : false;
                        break;
                    default:
                        break;
                }
            }
            dt.Rows.Add(dr);
        }

        (sender as RadGrid).DataSource = dt;
    }
}

 

If I type a letter into any cell of a row with an "I" or "R" in the second column, I want it to ignore that character.  The console.log() calls confirm that the variables in my JavaScript function are what I expect them to be, but the args.set_cancel(true) calls are not doing what I expect.

 

What do I need to do to get this character validation working?

What improvements/optimizations can be made to the OnKeyPress() function?

Attila Antal
Telerik team
 answered on 05 Apr 2022
0 answers
157 views

Hi Team,

I have an issue with OnClientClose and OnClientShow.

Its not firing when we call it from js file as mentioned in OnClientClose and OnClientShow.

Can anyone help me how to resolve this issue?

<telerik:RadWindowManager 
    id="WindowManager" runat="server" 
    OnClientClose = "Test.Extensions.Search.queryBuilderDialog.onSubmit"     (Replaced ClientCallBackFunction as OnClientClose)
    OnClientShow = "Test.Extensions.Search.queryBuilderDialog.onShow">
    <windows>
        <telerik:RadWindow id="TestWindow"                         
            Left="250px"
            Modal="true"
            Runat="server"
            Behaviors="Move,Resize,Close">
        </telerik:RadWindow>
    </windows>
</telerik:RadWindowManager>

Code of a Querydebug.JS file:

    Test.Extensions.Search.BuildQueryDialog.prototype = {
        //Properties
 queryBuilderDialog: null,
 this.queryBuilderDialog = new Test.Extensions.Search.BuildQueryDialog();
        radWindow: null,
        windowUrl: "",

        //Methods
        show: function (fieldId, isEdit) {
            var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft,
                scrollY = document.documentElement.scrollTop || document.body.scrollTop,
                viewPortWidth = $D.getClientWidth(),
                viewPortHeight = $D.getClientHeight(),
                elementWidth = 600,
                elementHeight = 400,
                x = (viewPortWidth / 2) - (elementWidth / 2) + scrollX,
                y = (viewPortHeight / 2) - (elementHeight / 2) + scrollY;

            this.radWindow = Test.Utilities.WindowUtil.getRADWindow("TestWindow");
            if (this.windowUrl === "")
                this.windowUrl = this.radWindow.GetUrl();

            var separator = (this.windowUrl.indexOf("?") == -1) ? "?" : "&";
            var url = this.windowUrl + separator + "id=" + fieldId + "&isedit=" + isEdit;
            this.radWindow.SetUrl(url);
            this.radWindow.Show();
            this.radWindow.MoveTo(x, y);
            this.radWindow.SetSize(elementWidth, elementHeight);
        },

        //Event Handlers
        onShow: function (radWindow) {
            var currentCondition = Test.Extensions.Search.queryBuilder.getCurrentCondition();

            //Set the argument object to the radWindow        
            radWindow.Argument = { conditionXml: $XML.SerializeXmlNode(currentCondition.toXml()) };
        },
        onClose: function (radWindow) { },
        onSubmit: function (radWindow, returnValue) {
            if (returnValue && returnValue.conditionXml) {
                var currentCondition = Test.Extensions.Search.queryBuilder.getCurrentCondition();
                currentCondition.fromXml(returnValue.conditionXml);
            }
        }
    };

Sachita
Top achievements
Rank 1
Iron
Iron
Iron
 updated question on 05 Apr 2022
1 answer
380 views

Hello,

 

i am trying to read the values of columns on button click in a telerik:GridTemplateColumn but seems not working


<telerik:RadGrid RenderMode="Lightweight" runat="server" AutoGenerateColumns="False" ID="RadGrid1"
AllowFilteringByColumn="false"  Width="100%" BorderWidth="0px" GridLines="Both"
AlternatingItemStyle-HorizontalAlign="Center" AllowSorting="false">
<MasterTableView TableLayout="Fixed" HeaderStyle-Font-Bold="true" ClientDataKeyNames="RepCRD" DataKeyNames="RepCRD" >
<Columns>
<telerik:GridBoundColumn DataField="RepCRD" Visible="false" HeaderText="RepCRD" UniqueName="RepCRD"  ReadOnly="True" />
<telerik:GridTemplateColumn HeaderText=""  UniqueName="AddAdv" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" AllowSorting="false" AllowFiltering="false">
<ItemTemplate>
<telerik:RadButton ID="btnAddAdv" CommandName="AddAdv" OnClick="btnAddAdv_Click" RenderMode="Lightweight" runat="server" AutoPostBack="true" Text="Add Advisor" />
<asp:Label ID="RepCRDlbl" Visible="false" Text='<%# Eval("RepCRD")%>' runat="server"></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridHyperLinkColumn HeaderText="CRD#" DataTextFormatString="{0}" DataNavigateUrlFields="RepCRD" Target="_blank" ItemStyle-HorizontalAlign="Center"  UniqueName="RepCRD"  DataTextField="RepCRD" />
<telerik:GridBoundColumn DataField="FullName" HeaderText="Name" SortExpression="FullName" UniqueName="FullName" ItemStyle-HorizontalAlign="Center" />
<telerik:GridHyperLinkColumn HeaderText="Broker/Dealer Firm CRD#" DataTextFormatString="{0}" DataNavigateUrlFields="BDFirmCRD" Target="_blank" ItemStyle-HorizontalAlign="Center" UniqueName="BDFirmCRD"  DataTextField="BDFirmCRD" />
<telerik:GridBoundColumn DataField="BrokerDealerName" HeaderText="Broker/Dealer Name" SortExpression="BrokerDealerName" UniqueName="BrokerDealerName" ItemStyle-HorizontalAlign="Center" />
<telerik:GridTemplateColumn HeaderText="" UniqueName="AddFirm1" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" AllowSorting="false" AllowFiltering="false">
<ItemTemplate>
<telerik:RadButton ID="btnAddFirm1" CommandName="AddFirm1" OnClick="btnAddFirm1_Click" RenderMode="Lightweight" runat="server" AutoPostBack="true" Text="Add Firm" />
<asp:hiddenfield ID="BDFirmCRDlbl"  Value='<%# Eval("BDFirmCRD")%>' runat="server"></asp:hiddenfield>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>

On Click of Button btnAddFirm1 it should read the BDFirmCRDlbl value like here


    Protected Sub btnAddFirm1_Click(sender As Object, e As EventArgs)
        Dim Button As RadButton = CType(sender, RadButton)
        Dim sBDFirmCRDlbl As String
        For Each item As GridDataItem In RadGrid1.MasterTableView.Items
            Dim strBDFirmCRD As String = item("BDFirmCRD").Text
            sBDFirmCRDlbl = (TryCast(item.FindControl("BDFirmCRDlbl"), HiddenField)).Value
        Next


    End Sub

the problem that it is only returning the last item in the grid and not the clicked value

 

Thanks

Doncho
Telerik team
 answered on 04 Apr 2022
1 answer
104 views

Hello,

I need a client-side solution that conditionally will not change the pager combo value.  I found an old thread here with some suggested client code at the bottom.  Basically, the pager's combo box selectedIndexChanging event is handled, and under given condition is canceled.  However, what I'm finding is that when not cancelled, the event is called twice.  Why is that, and how do I prevent?  Below is a simple example that demonstrates the issue.


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server">
    <meta charset="utf-8"/>
    <title></title>
    
    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
        <script type="text/javascript">

            function pageLoad(sender, eventArgs) {


            }

            function onCommand(sender, args) {
                args.set_cancel(true);

                var lsCommand = args.get_commandName();
                if (lsCommand == "PageSize") {
                    console.log('Got PageSize Command');
                }
            }

            function onMasterTableViewCreated(sender, args) {

                console.log('Creating selectedIndexChanging Handler');

                var pageSizeCombo = $telerik.findControl(sender.get_element(), "PageSizeComboBox");
                if (pageSizeCombo) {
                    pageSizeCombo.add_selectedIndexChanging(function (sender, args) {
                        //this method will fire before the combo changes the
                        //page size in the grid pager. You can cancel this event

                        // If condition is met, cancel
                        if (args.get_item().get_value() == "20") {
                            args.set_cancel(true);
                            console.log('Page Size change cancelled')
                        }
                        else {
                            console.log('Page Size change allowed');
                        }
                    });
                }
            }
        </script>
    </telerik:RadCodeBlock>

</head>
<body>
    <form id="form1" runat="server">
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server" />

        <telerik:RadStyleSheetManager id="RadStyleSheetManager1" runat="server" />

        <telerik:RadSkinManager ID="RadSkinManager1" runat="server" Skin="Default" ShowChooser="false" />

        <telerik:RadGrid ID="RadGrid1" runat="server"
            EnableViewState="false"
            AutoGenerateColumns="false" 
            AllowPaging="false" 
            AllowSorting="true"
            Width="100%"
            Height="150px"
        >
            <MasterTableView 
                    TableLayout="Fixed"
                    AllowNaturalSort="false" 
                    ClientDataKeyNames="Name"
                    AllowPaging="true" 
                    EnableViewState="false"
            >
                <Columns>
                    <telerik:GridBoundColumn DataField="Name"  UniqueName="Name"  DataType="System.String" HeaderText="Name"  HeaderStyle-Width="150px" />
                    <telerik:GridBoundColumn DataField="Count" UniqueName="Count" DataType="System.Int32" HeaderText="Count" HeaderStyle-Width="150px" />
                </Columns>
                <NoRecordsTemplate>
                    <table style="height: 120px; width:100%" border="0" cellpadding="0" cellspacing="0">
                        <tr>
                            <td align="center" valign="middle">
                                There are no files matching the search criteria.
                            </td>
                        </tr>
                    </table>
                </NoRecordsTemplate>
                <PagerStyle Mode="NextPrevAndNumeric" AlwaysVisible="true" PageSizes="10,20,50,100" />
            </MasterTableView>
            <ClientSettings>
                <ClientEvents 
                    OnCommand="onCommand"
                    OnMasterTableViewCreated="onMasterTableViewCreated"
                />
                <Selecting AllowRowSelect="true" />
                <Scrolling AllowScroll="true" UseStaticHeaders="true" />
                <DataBinding ShowEmptyRowsOnLoad="false" />
            </ClientSettings>
            <SortingSettings EnableSkinSortStyles="false" />
        </telerik:RadGrid>

    </form>
</body>
</html>



    public partial class Test2 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name", System.Type.GetType("System.String"));
            dt.Columns.Add("Count", System.Type.GetType("System.Int32"));

            DataRow dr = dt.NewRow();
            dr["Name"] = "Name1";
            dr["Count"] = 25;
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["Name"] = "Name2";
            dr["Count"] = 18;
            dt.Rows.Add(dr);

            RadGrid1.DataSource = dt;
            RadGrid1.DataBind();

            RadGrid1.MasterTableView.PageSize = 20;
        }
    }

Thanks,

Dave

Dave
Top achievements
Rank 1
Iron
Veteran
Iron
 answered on 04 Apr 2022
1 answer
289 views

When I use the Rad radio button and checkboxes... something is messing up the alignments.  I have reviewed my css, in page style changes and inspected the page in chrome and edge and I cannot find what is causing this (looks like all the applied styles are coming from Telerik.Web.

Any thoughts on where to fix this?

Peter Milchev
Telerik team
 answered on 04 Apr 2022
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
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
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?