Command Item Insert event

1 Answer 170 Views
Grid Window
Harlem98
Top achievements
Rank 1
Iron
Iron
Iron
Harlem98 asked on 09 Dec 2021, 11:48 PM | edited on 13 Dec 2021, 11:32 AM

Hello

I'm trying to perform insert operation in a RadWindow. My scenario integrates the searchbox selected value, which should not be editable and automatically filled in insert, and for the rest, the normal empty fields, including the primary key.

I've already done the edit operation, with the following structure, but i cannot modify properly to the insert. Besides, when i push Insert button, i get the last assinged values, as the radwindow does not perform reload

Could you help me please?


 public void SaveFile(object sender, EventArgs e)
        {
            ListagemTimesheet model = new ListagemTimesheet();
           
            model.IDRH = Convert.ToInt32(rdpIE.Text);
            model.IDState = Convert.ToInt32(rcbEstado.SelectedValue);
            model.Obs = Obstxt.Text;
            model.Assin = txtAssin.Text;
            model.Date = Date.SelectedDate.Value;

            if (Objecto.ID > 0)
            {
                model.ID = Convert.ToInt32(FileID.Text);

                if (!string.IsNullOrEmpty(FileID.Text) && Convert.ToInt32(FileID.Text) > 0)
                {
                    model.ID = Convert.ToInt32(FileID.Text);
                    bll.UpdateFile(model);

                }
                else
                {
 
                }
            }
            else //Insert

//Command item events


                if (e.CommandName == "EditItem")
                {
                    
                    try
                    {
                        string script = "function f(){openRadWindow(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
                        e.Canceled = true;

                        int idts= int.Parse(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString());
                        Dataclass ts= bll.GetFileByID(idts);
                        Editform.Object = ts;            
                        Editform.DataBind();
                        grid.Rebind();
                       
                      }


                    catch (System.Exception)
                    {
     
                    }

                    
                }

                    if (e.CommandName == "InsertItem")

//help

1 Answer, 1 is accepted

Sort by
0
Doncho
Telerik team
answered on 14 Dec 2021, 01:53 PM

Hi RĂºben,

Have you checked out our RadGrid - Window Editing demo?

I believe that the approach demonstrated in the demo is pretty handy and could be reused in similar cases.

Yet, If it is not applicable for the current scenario and it is not helping you achieve the desired it could be helpful if you share more information about the setup so we can have a better overview. Sharing the complete markup declaration of the RadGrid and RadWindow along with all relevant code-behind and JavaScript logic would help us understand the issue better.

Kind regards,
Doncho
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Harlem98
Top achievements
Rank 1
Iron
Iron
Iron
commented on 14 Dec 2021, 02:50 PM | edited

Hello Doncho!

In fact the scenario is not very usefull to my implementation. I was actually able to do the insert but i'm still with someproblems:

  1. I can´t open a window without a full refresh of the page for the second time, getting javascript error "Uncaught TypeError: Cannot read properties of null (reading 'show') at openRadWindow"
  2. I've  implemented a javascript radAlert, and i would like the page to perform a postback, which i'm not being able to achieve

Here is my implementation


//parent control JSfunction openRadWindow() { var radwindow = $find('<%=UserListDialog.ClientID %>'); radwindow.show(); } ´ //windowmanager parent control <div class="form" runat="server" id="divUC" > <telerik:RadWindowManager RenderMode="Lightweight" ID="radInfoWindow" runat="server" DestroyOnClose="true" CommandName="Confirmar" ShowContentDuringLoad="false" language="pt-PT"> <Windows> <telerik:RadWindow RenderMode="Lightweight" ID="UserListDialog" runat="server" Title="Editar Timesheets" Height="400px" Width="800px" Left="150px" ReloadOnShow="true" ShowContentDuringLoad="false" Modal="true" DestroyOnClose="true" VisibleStatusbar="False" Behaviors="Close,Move,Resize" CssClass="opaque" KeepInScreenBounds="True" AutoSize="false" > <ContentTemplate> <uc1:ViewEmissaoTimeSheetEdit ID="EditTimesheet" runat="server" /> </ContentTemplate> </telerik:RadWindow> </Windows> </telerik:RadWindowManager> //insert itemif (e.CommandName == "InitInsert") { //GridDataInsertItem insertedItem = e.Item as GridDataInsertItem; try { string script = "function f(){openRadWindow(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);"; ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true); //abrir window UserListDialog.DestroyOnClose = true; //limpar e.Canceled = true; //string idtimesheet = insertedItem.GetDataKeyValue("ID").ToString();//if (idtimesheet == null)//{ ListagemTimesheet timesheet = new ListagemTimesheet(); timesheet.IDRecursoHumano = int.Parse(rdpInvestigador.SelectedValue.ToString()); EditTimesheet.Objecto = timesheet; EditTimesheet.DataBind(); //} } //childcontrol radasyncuploadpublic void RadAsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e) { { RadAsyncUpload1.Visible = false; //false//var liItem = new HtmlGenericControl("li"); Ficheiro = e.File.FileName; //bind nome ficheiro FileTipo = e.File.ContentType; //bind formato ficheiro e.IsValid = true; e.File.InputStream.Position = 0; //criar a stream a partir da posiĂ§Ă£o inicial, para trabalhar com os bytes do ficheiro fileBytes = newbyte[e.File.InputStream.Length]; //criar a variavel, dando-lhe o tamanho do ficheirofor (int totalBytesCopied = 0; totalBytesCopied < e.File.InputStream.Length; ) //copiar todos os bytes do ficheiro para a variavel totalBytesCopied += e.File.InputStream.Read(fileBytes, totalBytesCopied, Convert.ToInt32(e.File.InputStream.Length) - totalBytesCopied); //copiar o ficheiro para var fileBytes e.File.InputStream.Close(); //terminar a manipulaĂ§Ă£o do ficheiro } } //Savemethod (..) some other code else// ID == 0 { ListagemTimesheet novo = new ListagemTimesheet(); //new list novo.IDRecursoHumano = Objecto.IDRecursoHumano; novo.IDEstadoTimesheet = Convert.ToInt32(rcbEstado.SelectedValue); novo.Observações = Obervaçoestxt.Text; novo.AssinaturaTimesheet = txtAssinaturaTimesheet.Text; novo.DataEnvio = DataEnvio.SelectedDate.Value; if (!string.IsNullOrEmpty(Ficheiro) && FileTipo != null) //configurar save das propriedades do ficheiro { novo.Ficheiro = Path.GetFileNameWithoutExtension(Ficheiro); novo.FileTipo = Path.GetExtension(Ficheiro); novo.FileContent = fileBytes; } if (!string.IsNullOrEmpty(FileID.Text) && Convert.ToInt32(FileID.Text) == 0) { //novo.ID = Convert.ToInt32(FileID.Text); listagembll.InsertFile(novo); //insert in DB method

            RadScriptManager.RegisterStartupScript(Page, Page.GetType(), "1", "Sys.Application.add_load(function(){{alert('O registo foi adicionado com sucesso!');}}, 500);", true); }

//Child control JS

function GetRadWindow() {
        var oWindow = null;
        if (window.radWindow) oWindow = window.radWindow; //Will work in Moz in all cases, including clasic dialog
        else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow; //IE (and Moz as well)

        return oWindow;
    }

    function CloseAndRebind() {
        function callbackFn(arg)//the value indicates how the dialog was closed
        {
            GetRadWindow().BrowserWindow.refreshGrid(args);
            GetRadWindow().close();
        }
        radalert('Data Saved successfully', 330, 100, 'Client RadAlert', callbackFn);
    }

    function CancelEdit() {
        GetRadWindow().close();
    }

    function closeWindow() {
        var oWindow = GetRadWindow();
        oWindow.OnClientClose = CloseAndRebind;
    }

Doncho
Telerik team
commented on 17 Dec 2021, 12:12 PM

Hi RĂºben,

Please try to move the RadWindow out of the RadWindowManager as a standalone control on the page as noted at the end of the Using RadWindow as Controls Container article:

"When controls with complex server life cycle are placed in the ContentTemplate (e.g., a RadGrid ), such RadWindows should be kept outside of a RadWindowManager. The manager maintains the Windows collection and sometimes needs to Clear() and recreate it, which can cause unexpected behavior with the server logic of the complex controls inside."

Another thing you can try is to set the EnableViewState property of the RadWindowManager to false, as mentioned at the end of the Opening from the Server article.

If none of these helps, it would be very helpful if you share a FiddlerJam capture of the current behavior so we can have a better understanding of the problem - Capture ASP.NET Web Forms network logs & log issues with Fiddler Jam

Harlem98
Top achievements
Rank 1
Iron
Iron
Iron
commented on 17 Dec 2021, 03:43 PM | edited

Hello Doncho

I've tried your suggested approaches, without any change in the behaviour. I also tried to perform a postback at rad alert, when window closes, also with no success.

Here's a Fiddler jam sample so you could see with more details. Normal behaviour in first operation, and crashes at the second one. It's also the same if i do 2 times the same opeartion, or insert and then edit.

https://jam.getfiddler.com/sessions/210abce2-1fdc-4d39-9cde-88b5e00f41fa?t=d528fea32c2d9acfdc1364677d2f75603dc0d901de9d4becde98aaee93b0c024e2bc0a21dc1f394d9cde88b5e00f41fa

Doncho
Telerik team
commented on 22 Dec 2021, 12:04 PM

Thank you for your cooperation, RĂºben!

Unfortunately, the provided Fiddler Jam capture has not enough information included. This is most likely due to the missing initial load of the page in the capture.

Recently Fiddler Jam tool has been updated with a new feature that provides a more straightforward way to capture a fully functional log. We have updated the Capture ASP.NET Web Forms network logs & log issues with Fiddler Jam with the recent instructions for creating a useful capture in the most convenient way (make sure that the article is not loaded from the browser's cache - Ctrl+F5).

Could you please uninstall the extension and install it anew to make sure you are using its latest version and recapture the problem again but this time by using the link below

Additionally it would be very helpful if you share the complete code structure so we can have a more clear overview of the case. The whole aspx and aspx.cs and also the WebUserControl nested in the RadWindow would help us ge a better understanding of the current scenario.

Harlem98
Top achievements
Rank 1
Iron
Iron
Iron
commented on 22 Dec 2021, 08:18 PM

Hi Doncho. I've managed to overcome this first issue, don't really know how... ajax isssues probably

But, yet more problems, now i can do several multiple operations, but only the first one is done correctly, on the second forwards, DatePicker and ComboBox values remain the same from the previous operation, and RadAsyncUpload just disapears. It´s probably not my code, because i also have TextBox's which are cleaning the values normally (except for the first one, which is programatically suposed).

Any ideas on this one? On my comment above (14th December, you can see my code)

I also send you another sample https://jam.getfiddler.com/sessions/f1a806dd-3a67-4a56-96c3-64137631945f?t=1bdfde0b2dd013e8fa5406492ad0f3de92cad79b79952370887b1df8831cf9f8dd06a8f1673a564a96c364137631945f

The attachment shows the issues

 

Doncho
Telerik team
commented on 23 Dec 2021, 11:54 AM

Hi RĂºben,

I am afraid that the initial load of the page is again missing in the provided Fiddler Jam capture. Without the initial request, I am not able to mock and investigate the behavior.

On the other hand, even if the capture is complete it most probably will not be enough for us to troubleshoot the problem.

In order to help you further with this issue, I would need a reproduction of the problem that I can run and debug locally.

Please isolate the problem into a runnable sample and share it so we can investigate it locally, check out Isolating a Problem in a Sample Project.


Harlem98
Top achievements
Rank 1
Iron
Iron
Iron
commented on 23 Dec 2021, 02:46 PM

Unfortunately i can't share a workable sample, because of the scope of the application. 

Do you have any suggestion anyways? It is a common issue?

Vessy
Telerik team
commented on 28 Dec 2021, 07:19 AM

Hi RĂºben,

Can you try giving some timeout to the RadWindow-opening logic and see if the problem persists? You could increase/decrease the timeout value as needed:

string script = "function f(){setTimeout(openRadWindow, 1000); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true); //abrir window

Harlem98
Top achievements
Rank 1
Iron
Iron
Iron
commented on 28 Dec 2021, 10:33 AM | edited

Hello Vessy.

Thank you for your suggestion, but unfortunately the problem persists with the timeout.

I've managed to clean the the remaining atributes on my form by cleaning atributes values programatically. 

But on RadAsyncUpload this does not solve the issue, because the RadAsyncUpload simply disapears.

Note: If I use RadWindowManager and nest radWindow in it, i'm not able to perform the operation, maybe this was a solver it  worked?

 

Attila Antal
Telerik team
commented on 29 Dec 2021, 01:41 PM

Hi RĂºben.

We are not aware of a known problem with the error message you shared. In order to be able to investigate the problem and see whether it's a bug or the custom code fails, we need more information. If you cannot share the ASPX/ASPX.CS pages with us, then try to describe the steps that will help us replicate the issue. 

Without seeing the code, we are only making wild guesses. For a more accurate answer, we need to see the code.

Thank you for your understanding.

Harlem98
Top achievements
Rank 1
Iron
Iron
Iron
commented on 29 Dec 2021, 02:24 PM | edited

Helllo Attila

I understand that it is hard with incomplete information, i'm sorry. I was counting that it was a common issue, but i actually haven't find anyone relating my specific problem.

In my parent control i use:

 

<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server"><script> //other JS functions in page //UI SearchBox function OnClientSelectedIndexChangedEventHandler(sender, args) { var grid = $find("<%=gvTimesheets.ClientID %>"); grid.get_masterTableView().filter("IDRecursoHumano", args.get_item().get_value(), "EqualTo"); } function OnClientBlurHandler(sender, eventArgs) { var textInTheCombo = sender.get_text(); var item = sender.findItemByText(textInTheCombo); //if there is no item with that text if (!item) { sender.clearSelection(); sender.set_emptyMessage(" - escolher - "); } } //delete alert and confirm function buttonDeleteClicked() { alert('A versĂ£o foi apagada com sucesso!'); } function StandardConfirmD(sender, args) { var validated = Page_ClientValidate('Val'); if (!validated) return; args.set_cancel(!window.confirm("Tem a certeza que pretende eliminar a versĂ£o selecionada da lista? NĂ£o poderĂ¡ refazer a acĂ§Ă£o.")); } //Desativar Msgs labels setTimeout(function () { var alerts = document.getElementsByClassName("labelM"); for (var i = 0; i < alerts.length; i++) { alerts[i].style.display = "none"; } }, 5000); // Disabling ajax for file download function exportStats() { funcDownloadSemAjax(); var currentLoadingPanel = $find("<%= RadAjaxLoadingPanel1.ClientID %>"); currentLoadingPanel.show("<%= divTimesheet.ClientID %>"); //initiate cookie polling appendDownloadToken(); } function appendDownloadToken() { window._downloadToken = new Date().getTime() + ""; //add a form field containing the download token before submit $telerik.$("<input type='hidden' id='_downloadToken' name='_downloadToken' value='" + window._downloadToken + "' />").appendTo(document.forms[0]); pollDownloadCookie(); } function pollDownloadCookie() { //compare cookie value and initial value if (cookie.get("_downloadToken") === window._downloadToken) { //erase download token cookie cookie.erase("_downloadToken"); //remove the token value window[_downloadToken] = undefined; try { delete window[_downloadToken]; } catch (e) { } //remove the form field $telerik.$("#_downloadToken").remove(); //hide the loading panel $find("<%= RadAjaxLoadingPanel1.ClientID %>").hide("<%= divTimesheet.ClientID %>"); } else { setTimeout(pollDownloadCookie, 100); } } //window functions function openRadWindow() { var radwindow = $find('<%=UserListDialog.ClientID %>'); radwindow.show(); } function OnClientCloseHandler(sender, args) { var data = args.get_argument(); if (data) { alert(data); } } <telerik:RadWindow ID="UserListDialog" runat="server" Title="Atualizar listagem" Height="400px" OnClientClose="OnClientCloseHandler" Width="800px" Left="150px" ReloadOnShow="true" ShowContentDuringLoad="false" DestroyOnClose="true" Modal="true" Behaviors="Close,Move,Resize" CssClass="opaque" KeepInScreenBounds="True" > <ContentTemplate> <uc1:ViewEmissaoTimeSheetEdit ID="EditTimesheet" runat="server" /> </ContentTemplate> </telerik:RadWindow> </script></telerik:RadCodeBlock>

// (...) Grid code

Child user control, containing the form


//windowfunction GetRadWindow() { var oWindow = null; if (window.radWindow) oWindow = window.radWindow; //Will work in Moz in all cases, including clasic dialogelseif (window.frameElement.radWindow) oWindow = window.frameElement.radWindow; //IE (and Moz as well)return oWindow; } function CloseOnReload() { GetRadWindow().Close(); } function refreshParentPage() { GetRadWindow().BrowserWindow.location.reload(); } function clientClose(arg) { getRadWindow().close(arg); }

(...) form attributes

My save method, in child.ascx.cs


Save file
{

{
(...)
}

RadScriptManager.RegisterStartupScript(Page, Page.GetType(), "1", "Sys.Application.add_load(function(){{alert('O registo foi adicionado com sucesso!');}}, 500);",  true);
}

 

 

Attila Antal
Telerik team
commented on 03 Jan 2022, 09:13 AM

Hi Ruben,

Firstly I would like to wish you a Happy New Year 2022!

As for the issue, I'm afraid the provided information is not enough to replicate the described behavior. We do not see which exact events are used, which controls trigger the events and from which page (Content Page or UserControl). We need to see the complete structure that includes the content of .aspx, .asxp.cs + .ascx, .ascx.cs. 

Please create an isolated version of the issue (create a Visual Studio solution or just share the ASPX and ASCX files zipped. We will run the solution and by seeing the problem we will be able to tell you exactly where is the issue.

I suggest that you submit a Formal Support Ticket. There we can exchange information without making it public. You will also receive a much quicker response time.

 

Tags
Grid Window
Asked by
Harlem98
Top achievements
Rank 1
Iron
Iron
Iron
Answers by
Doncho
Telerik team
Share this question
or