[CLOSED] Deleting Selected row using Direct Method

  1. #1

    [CLOSED] Deleting Selected row using Direct Method

    Considering the sample below where i am using a [Direct Method] ValidateSave to delete the record from the back end


    <%@ Page Language="C#" %>
    
    <%@ Import Namespace="System.Collections.ObjectModel" %>
    <%@ Import Namespace="System.Collections.Generic" %>
    
    <%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
    
    <script runat="server">
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                Store store = this.GridPanel1.GetStore();
                
                store.DataSource = new List<object>
                {
                    new { 
                        Name = "Bill Foot", 
                        Email = "bill.foot@object.net", 
                        Start = new DateTime(2007, 2, 5), 
                        Salary = 37000, 
                        Active = true
                    },
                    new { 
                        Name = "Bill Little", 
                        Email = "bill.little@object.net", 
                        Start = new DateTime(2009, 6, 13), 
                        Salary = 53000, 
                        Active = true
                    },
                    new { 
                        Name = "Bob Jones", 
                        Email = "bob.jones@object.net", 
                        Start = new DateTime(2008, 10, 6), 
                        Salary = 70000, 
                        Active = true
                    },
                    new { 
                        Name = "Bob Train", 
                        Email = "bob.train@object.net", 
                        Start = new DateTime(2009, 5, 5), 
                        Salary = 68000, 
                        Active = true
                    },
                    new { 
                        Name = "Chris Johnson", 
                        Email = "chris.johnson@object.net", 
                        Start = new DateTime(2009, 1, 25), 
                        Salary = 47000, 
                        Active = true
                    }
                };
                
                store.DataBind();
            }
        }
    
        [DirectMethod]
        public object ValidateSave(bool isPhantom, JsonObject values)
        {
            if (!isPhantom)
            {
                return new { valid = true };
            }
    
            if (!values.ContainsKey("salary") || Convert.ToInt32(values["salary"]) < 1000)
            {
                return new { valid = false, msg = "Salary must be >=1000 for new employee" };
            }
    
            return new { valid = true };
        }
    </script>
    
    <!DOCTYPE html>
        
    <html>
    <head runat="server">
        <title>GridPanel with RowEditor Plugin - Ext.NET Examples</title>
        <link href="/resources/css/examples.css" rel="stylesheet" />
        
        <ext:XScript runat="server">
            <script>
                var addEmployee = function () {
                    var grid = #{GridPanel1};
                    grid.editingPlugin.cancelEdit();
    
                    // Create a record instance through the ModelManager
                    var r = Ext.ModelManager.create({
                        name: 'New Guy',
                        email: 'new@object.net',
                        start: new Date(),
                        salary: 500,
                        active: true
                    }, 'Employee');
    
                    grid.store.insert(0, r);
                    grid.editingPlugin.startEdit(0, 0);
                };
                
                var removeEmployee = function () {
                    var grid = #{GridPanel1},
                        sm = grid.getSelectionModel();
    
                    grid.editingPlugin.cancelEdit();
                    grid.store.remove(sm.getSelection());
                    if (grid.store.getCount() > 0) {
                        sm.select(0);
                    }
                };
    
                var validateSave = function () {                
                    var plugin = this.editingPlugin;
                    if (this.getForm().isValid()) { // local validation                    
                        App.direct.ValidateSave(plugin.context.record.phantom, this.getValues(false, false, false, true), {
                            success : function (result) {
                                if (!result.valid) {
                                    Ext.Msg.alert("Error", result.msg);
                                    return;
                                }
    
                                plugin.completeEdit();
                            }
                        });
                    }
                };
            </script>
        </ext:XScript>
    </head>
    <body>
        <form runat="server">
            <ext:ResourceManager runat="server" />
            
            <h1>GridPanel with RowEditor Plugin and remote confirmation</h1>
            
            <ext:GridPanel 
                ID="GridPanel1" 
                runat="server"
                Width="600"
                Height="400"
                Frame="true"
                Title="Employees">
                <Store>
                    <ext:Store ID="Store1" runat="server">
                        <Sorters>
                            <ext:DataSorter Property="start" Direction="ASC" />
                        </Sorters>
                        <Model>
                            <ext:Model runat="server" Name="Employee">
                                <Fields>
                                    <ext:ModelField Name="name" ServerMapping="Name" Type="String" />
                                    <ext:ModelField Name="email" ServerMapping="Email" Type="String" />
                                    <ext:ModelField Name="start" ServerMapping="Start" Type="Date" />
                                    <ext:ModelField Name="salary" ServerMapping="Salary" Type="Float" />
                                    <ext:ModelField Name="active" ServerMapping="Active" Type="Boolean" />
                                </Fields>
                            </ext:Model>
                        </Model>
                    </ext:Store>
                </Store>
                <Plugins>
                    <ext:RowEditing runat="server" ClicksToMoveEditor="1" AutoCancel="false" SaveHandler="validateSave" />
                </Plugins>            
                <TopBar>
                    <ext:Toolbar runat="server">
                        <Items>
                            <ext:Button runat="server" Text="Add Employee" Icon="UserAdd">
                                <Listeners>
                                    <Click Fn="addEmployee" />
                                </Listeners>
                            </ext:Button>
                            <ext:Button ID="btnRemoveEmployee" runat="server" Text="Remove Employee" Icon="UserDelete" Disabled="true">
                                <Listeners>
                                    <Click Fn="removeEmployee" />
                                </Listeners>
                            </ext:Button>
                        </Items>
                    </ext:Toolbar>
                </TopBar>            
                <ColumnModel>
                    <Columns>
                        <ext:RowNumbererColumn runat="server" Width="25" />
                        <ext:Column runat="server"                         
                            Text="Name" 
                            DataIndex="name" 
                            Flex="1">
                            <Editor>
                                <ext:TextField runat="server" AllowBlank="false" />
                            </Editor>
                        </ext:Column>
                        <ext:Column runat="server" Text="Email" DataIndex="email" Width="160">
                            <Editor>
                                <ext:TextField runat="server" AllowBlank="false" Vtype="email" />
                            </Editor>
                        </ext:Column>
                        <ext:DateColumn runat="server" 
                            Text="Start Date" 
                            DataIndex="start" 
                            Format="MM/dd/yyyy" 
                            Width="100">
                            <Editor>
                                <ext:DateField 
                                    runat="server" 
                                    AllowBlank="false" 
                                    Format="MM/dd/yyyy"
                                    MinDate="01.01.2006" 
                                    MinText="Can not have a start date before the Company existed." 
                                    MaxDate="<%# DateTime.Now %>"
                                    AutoDataBind="true"
                                    />
                            </Editor>
                        </ext:DateColumn>
                        <ext:NumberColumn
                            runat="server"
                            Text="Salary" 
                            DataIndex="salary" 
                            Format="$0,0">
                            <Editor>
                                <ext:NumberField 
                                    runat="server" 
                                    AllowBlank="false" 
                                    MinValue="1" 
                                    MaxValue="150000" 
                                    />
                            </Editor>
                        </ext:NumberColumn>
                        <ext:CheckColumn
                            runat="server"
                            Text="Active?" 
                            DataIndex="active"                         
                            Width="50">
                            <Editor>
                                <ext:Checkbox runat="server" Cls="x-grid-checkheader-editor" />
                            </Editor>
                        </ext:CheckColumn>
                    </Columns>
                </ColumnModel>
                <Listeners>
                    <SelectionChange Handler="#{btnRemoveEmployee}.setDisabled(!selected.length);" />
                </Listeners>
            </ext:GridPanel>
        </form>  
    </body>
    </html>
    When I try to use the same concept to delete the record it am struggling to pass the Record Selected
    added the following call at the javascript function removeEmployee
     App.direct.ValidateDelete(this.getValues(false, false, false, true));
    and aspx.cs.
    [DirectMethod]
            public object ValidateDelete(JsonObject values)
            {
               XmlNode xml = JSON.DeserializeXmlNode("{records:{record:" + values + "}}");
               foreach (XmlNode row in xml.SelectNodes("records/record"))
               { 
    
               }
                return new { valid = true };
            }
    I get the following error:

    Microsoft JScript runtime error: Object doesn't support property or method 'getValues'
    Last edited by Baidaly; Aug 09, 2013 at 12:18 AM. Reason: [CLOSED]
  2. #2
    Hi @otouri,

    Probably, the scopes (this reference) are not the same in the places where you call those DirectMethods.

    You can get the selected records from a GridPanel.
    grid.getRowsValues({ selectedOnly: true });
  3. #3
    After updating the code to:
     var removeWireInstruction = function () {
                    var grid = #{gpWireInstruction},
                        sm = grid.getSelectionModel();
    
                    grid.editingPlugin.cancelEdit();
                    grid.store.remove(sm.getSelection());
                    App.direct.ValidateDelete(grid.getRowsValues({ selectedOnly: true }));
                    if (grid.store.getCount() > 0) {
                        sm.select(0);
                    }
                };
    I get the following errors:
    Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Ext.Net.JsonObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '', line 1, position 1. at Newtonsoft.Json.Serialization.JsonSerializerIntern alReader.EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract) at Newtonsoft.Json.Serialization.JsonSerializerIntern alReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id) at Newtonsoft.Json.Serialization.JsonSerializerIntern alReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) at Newtonsoft.Json.Serialization.JsonSerializerIntern alReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) at Newtonsoft.Json.JsonSerializer.DeserializeInternal (JsonReader reader, Type objectType) at Newtonsoft.Json.JsonSerializer.Deserialize(JsonRea der reader, Type objectType) at Newtonsoft.Json.JsonConvert.DeserializeObject(Stri ng value, Type type, JsonSerializerSettings settings) at Ext.Net.JSON.Deserialize(String value, Type type, List`1 converters, IContractResolver resolver) at Ext.Net.JSON.Deserialize(String value, Type type) at Ext.Net.DirectMethod.Invoke(Object target, HttpContext context, ParameterCollection args) at Ext.Net.DirectMethod.Invoke(Object target, ParameterCollection args) at Ext.Net.ResourceManager.RaisePostBackEvent(String eventArgument)
  4. #4
    The exception details looks self-explained.

    The getRowsValues method returns an JSON array, you are seems trying to deserialize it into a JSON object.
  5. #5
    Thank you for the catch. I have updated the code behind to JSON array,:
    [DirectMethod]
            public object ValidateDelete( JsonObject [] values)
            {
                XmlNode xml = JSON.DeserializeXmlNode("{records:{record:" + values + "}}");
                foreach (XmlNode row in xml.SelectNodes("records/record"))
                { 
    
                }
               X.Msg.Alert("GetSelectedRow", this.gpWireInstruction.GetSelectionModel());
                return new { valid = true };
            }
    but now i get the following error:
    JsonReaderExcepection was unhandled by user code: Unexpected character encountered while parsing value: E. Path 'records.record', line 1, position 17.
    I modified my javascript call to encode the getRowsValues but i am still getting the error:
           var removeWireInstruction = function () {
                    var grid = #{gpWireInstruction},
                        sm = grid.getSelectionModel();
    
                    grid.editingPlugin.cancelEdit();
                    grid.store.remove(sm.getSelection());
                    //App.direct.ValidateDelete(grid.getRowsValues({ selectedOnly: true }));
                    App.direct.ValidateDelete(Ext.encode(#{gpWireInstruction}.getRowsValues({selectedOnly:true})));
                    if (grid.store.getCount() > 0) {
                        sm.select(0);
                    }
                };
  6. #6
    XmlNode xml = JSON.DeserializeXmlNode("{records:{record:" + values + "}}");
    Do you assume that a single row only can be selected?

    If so, you can try:
    grid.getSelectionModel().getSelection()[0].data
    instead of the getRowsValues method.
  7. #7
    Yes it's a single row selection

    I implemented your suggestion and now i get the following error:
    Microsoft JScript runtime error: Unable to get value of the property 'data': object is null or undefined
     var removeWireInstruction = function () {
                    var grid = App.MainContent_gpWireInstruction,
                        sm = grid.getSelectionModel();
    
                    grid.editingPlugin.cancelEdit();
                    grid.store.remove(sm.getSelection());
                    //App.direct.ValidateDelete(grid.getRowsValues({ selectedOnly: true }));
                    App.direct.ValidateDelete(grid.getSelectionModel().getSelection()[0].data);
                    if (grid.store.getCount() > 0) {
                        sm.select(0);
                    }
                };
  8. #8
    Basically what I am trying to do is delete from the database the selected row. so i need the values of that row to grab the ID and other data.
    If it can't be done the way i am trying to accomplish it please suggest another work around.
  9. #9

    Solved

    This thread can be closed. I used another approche

    Sharing the solution:

     <ext:Button ID="btnRemoveWireInstruction" runat="server" Text="Remove WireInstruction"
                                                            Icon="BookDelete" Disabled="true">
                                                            <DirectEvents>
                                                                <Click OnEvent="SubmitSelection">
                                                                    <ExtraParams>
                                                                        <ext:Parameter Name="Values" Value="Ext.encode(#{gpWireInstruction}.getSelectionModel().getSelection()[0].data)"
                                                                            Mode="Raw" />
                                                                    </ExtraParams>
                                                                </Click>
                                                            </DirectEvents>
                                                        </ext:Button>
     protected void SubmitSelection(object sender, DirectEventArgs e)
            {
        
                byte? RankWireInstruction;
                RankWireInstruction = null;
    
                XmlNode xml = JSON.DeserializeXmlNode("{records:{record:" + e.ExtraParams["Values"] + "}}");
    
                foreach (XmlNode row in xml.SelectNodes("records/record"))
                {
                    if (row.SelectSingleNode("RankWireInstruction").InnerXml != null)
                    {
                        if (row.SelectSingleNode("RankWireInstruction").InnerXml != "")
                        {
                            RankWireInstruction = Convert.ToByte(row.SelectSingleNode("RankWireInstruction").InnerXml);
                        }
                    }
                }
    
            }
    Thank you for your help.

Similar Threads

  1. [CLOSED] Output Cache issue with Direct Method / Direct Event
    By amitpareek in forum 1.x Legacy Premium Help
    Replies: 18
    Last Post: Mar 01, 2013, 5:03 AM
  2. [CLOSED] how to call direct method
    By tactime10 in forum 2.x Legacy Premium Help
    Replies: 2
    Last Post: Oct 04, 2012, 8:38 AM
  3. [CLOSED] MVC - Direct Method
    By adelaney in forum 2.x Legacy Premium Help
    Replies: 1
    Last Post: Jun 19, 2012, 9:43 PM
  4. [CLOSED] Direct Method in UX
    By dev in forum 1.x Legacy Premium Help
    Replies: 2
    Last Post: May 30, 2012, 12:32 PM
  5. Direct method and direct event over SSL?
    By dimitar in forum 1.x Help
    Replies: 0
    Last Post: Oct 08, 2011, 8:09 PM

Posting Permissions