[CLOSED] MenuPanel Get Selected MenuItem from client side (javascript)

  1. #1

    [CLOSED] MenuPanel Get Selected MenuItem from client side (javascript)

    Guys,

    I've been searching through the examples and the forum and haven't found the correct way to get the currently selected menuItem of a MenuPanel from client side.

    Thanks!
    Jason
    Last edited by Daniil; Nov 26, 2011 at 3:25 PM. Reason: [CLOSED]
  2. #2
    Hi,

    Please look at the example.

    Example

    <%@ Page Language="C#" %>
    
    <%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
    
    <!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>Ext.Net Example</title>
    
        <script type="text/javascript">
            var getSelectedItem = function (mp) {
                var index = parseInt(mp.getSelIndexField().getValue()),
                    item;
                if (!isNaN(index)) {
                    item = MenuPanel1.menu.items.get(index);
                }
                alert(item ? item.text : "No selected item");
            };
        </script>
    </head>
    <body>
        <form runat="server">
            <ext:ResourceManager runat="server" />
            <ext:MenuPanel ID="MenuPanel1" runat="server">
                <Menu runat="server">
                    <Items>
                        <ext:MenuItem Text="Item 1" />
                        <ext:MenuItem Text="Item 2" />
                    </Items>
                </Menu>
            </ext:MenuPanel>
            <ext:Button runat="server" Text="Get a selected index">
                <Listeners>
                    <Click Handler="getSelectedItem(MenuPanel1);" />
                </Listeners>
            </ext:Button>
        </form>
    </body>
    </html>
    Last edited by Daniil; Nov 23, 2011 at 2:34 PM.
  3. #3
    Perfect! That worked...thanks so much. Feel free to close this...
    Jason
  4. #4

    Next Step

    Thanks for that, it works just fine. I now need to know how to set the selected index of the menu once I have removed an item from the collection, or adding a new one. This manipulation will be done through a direct event or direct method. Once I delete an item I would like to set the menu index back to zero.

    Thanks!

    Here's some sample code:

    Markup:
    <ext:Panel ID="pnlProducts" runat="server" Icon="Package" Title="Products" Padding="10" Border="false" Layout="BorderLayout">
        <Items>
            <ext:MenuPanel ID="mpProducts" runat="server" Selectable="true" SelectedIndex="0" Region="West" Width="200">
                <Menu ID="mItems" runat="server" ShowSeparator="false">
                    <Listeners>
                        <ItemClick Fn="menuItemClick" />
                    </Listeners>
                </Menu>
            </ext:MenuPanel>
            <ext:Panel ID="pnlProductDetail" runat="server" Title="Product Info" AutoScroll="true" Region="Center">
                <TopBar>
                    <ext:Toolbar ID="toolProduct" runat="server">
                        <Items>
                            <ext:ToolbarFill ID="ToolbarFill4" runat="server" />
                            <ext:Button ID="btnAddProduct" runat="server" Icon="Add" Text="Add">
                                <Listeners>
                                    <Click Handler="#{productWindow}.show();" />
                                </Listeners>
                            </ext:Button>
                            <ext:Button ID="btnDeleteProduct" runat="server" Icon="Delete" Text="Delete Selected">
                                <DirectEvents>
                                    <Click OnEvent="btnDeleteProduct_Click">
                                        <Confirmation ConfirmRequest="true" Message="Are you sure you want to delete the selected product?" />
                                        <ExtraParams>
                                            <ext:Parameter Name="productId" Value="menu_getSelectedId(#{mpProducts})" Mode="Raw">
                                            </ext:Parameter>
                                        </ExtraParams>
                                    </Click>
                                </DirectEvents>
                            </ext:Button>
                        </Items>
                    </ext:Toolbar>
                </TopBar>
            </ext:Panel>
        </Items>
    </ext:Panel>
    Script:

    var menu_getSelectedId = function (m) {
        var selectedIds = [];
        var index = parseInt(m.getSelIndexField().getValue());
        var item; 
        
        if (!isNaN(index)) { 
            item = m.menu.items.get(index); 
            selectedIds.push(item.productid); 
        } 
    
        return Ext.encode(selectedIds);
    }
    Code Behind:

    protected void btnDeleteProduct_Click(object sender, DirectEventArgs e)
    {
        int[] ids = JSON.Deserialize<int[]>(e.ExtraParams["productId"]);
        DeleteProduct(ids);
    }
    
    public bool DeleteProduct(int[] ProductIds)
    {
        bool returnVal = false;
        if (ProductIds.IsNotNull())
        {
            try
            {
                foreach (int ProductId in ProductIds)
                {
                    RxGroupProductService.Instance.Delete(ProductId);
                }
                
                LoadData();
                LoadProductsMenu();
                mpProducts.SetSelectedIndex(mpProducts.Menu.Items.Count - 1);
                pnlProductDetail.UpdateContent();
                mpProducts.Menu.UpdateContent();
    
                returnVal = true;
            }
            catch (Exception ex)
            {
                Ext.Net.X.Msg.Show(new MessageBoxConfig{
                    Title = "Error deleting product",
                    Message = ex.Message,
                    Icon = MessageBox.Icon.ERROR,
                    Buttons = MessageBox.Button.OK
                });
            }
        }
    
        return returnVal;
    }
    
    private void LoadProductsMenu()
    {
        mpProducts.Menu.Items.Clear();
        pnlProductDetail.Items.Clear();
        RxGroupData.RxGroupProductCollection.ForEach(rxp =>
        {
            RxGroupProductService.Instance.DeepLoad(rxp, false, DAL.DeepLoadType.IncludeChildren,
                typeof(Product));
    
            Ext.Net.MenuItem mi = new Ext.Net.MenuItem();
            mi.Text = rxp.ProductIdSource.Name;
            mi.CustomConfig.Add(new ConfigItem("productid", rxp.RxGroupProductId.ToString()));
            mpProducts.Menu.Items.Add(mi);
        });
    
        if (mpProducts.Menu.Items.Count > 0)
        {
            RxGroupProduct rxp = RxGroupProductService.Instance.GetByRxGroupProductId(mpProducts.Menu.Items[0].CustomConfig[0].Value.ChangeType<int>());
    
            ProductDetailForm pdf = new ProductDetailForm(rxp.ProductId, ItemIdAsInt32);
            pnlProductDetail.Items.Add(pdf);
        }
        else
        {
            Ext.Net.MenuItem mi = new Ext.Net.MenuItem();
            mi.Text = "No Products";
            mi.CustomConfig.Add(new ConfigItem("productid", "0"));
            mpProducts.Menu.Items.Add(mi);
    
            ProductDetailForm pdf = new ProductDetailForm(0, ItemIdAsInt32);
            pnlProductDetail.Items.Add(pdf);
        }
    }
  5. #5
    Please use the setSelectedIndex method:
    MenuPanel1.setSelectedIndex(0);
  6. #6

    Already Tried That

    Thanks Daniil for you response, but you may notice that in my example I provided I am already using that line of code. Unfortunately, this does produce the desired effect. What happens is that no menu item is selected.

    When I delete an item:
    1. Delete the item from the database
    2. Reload my collection from the database
    3. Clear the menu items from the Menu control
    4. Create the new menu list of menu items
    5. If there is nothing in the colleciton from the database, I add a dummy menu item to show that there are no products assigned.

    This entire process is executed from within a direct event handler. Am I missing something?

    Thanks!
  7. #7

    Some More Sample Code

    Please see this example as well:

    <%@ Page Language="C#" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <script runat="server">
        public class Product
        {
            public Product()
            {
    
            }
    
            public int ProductId { get; set; }
            public string Name { get; set; }
        }
    
        public List<Product> MyProducts
        {
            get
            {
                if (Session["products"] == null)
                {
                    List<Product> products = new List<Product>();
                    products.Add(new Product() { ProductId = 1, Name = "Healthcare Benefit Savings" });
                    products.Add(new Product() { ProductId = 2, Name = "Care Package" });
                    Session["products"] = products;
                }
                return (List<Product>)Session["products"];
            }
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack && !X.IsAjaxRequest)
            {
                LoadProductsMenu();
            }
        }
    
        private void LoadProductsMenu()
        {
            mpProducts.Menu.Items.Clear();
            pnlProductDetail.Items.Clear();
    
            MyProducts.ForEach(p =>
            {
                Ext.Net.MenuItem mi = new Ext.Net.MenuItem();
                mi.Text = p.Name;
                mi.CustomConfig.Add(new ConfigItem("productid", p.ProductId.ToString()));
    
                mpProducts.Menu.Items.Add(mi);
            });
    
            if (mpProducts.Menu.Items.Count > 0)
            {
                ProductDetailForm pdf = new ProductDetailForm(Convert.ToInt32(mpProducts.Menu.Items[0].CustomConfig[0].Value));
                pnlProductDetail.Items.Add(pdf);
            }
            else
            {
                Ext.Net.MenuItem mi = new Ext.Net.MenuItem();
                mi.Text = "No Products";
                mi.CustomConfig.Add(new ConfigItem("productid", "0"));
                mpProducts.Menu.Items.Add(mi);
    
                ProductDetailForm pdf = new ProductDetailForm(0);
                pnlProductDetail.Items.Add(pdf);
            }
        }
    
        protected void btnDeleteProduct_Click(object sender, DirectEventArgs e)
        {
            int[] ids = JSON.Deserialize<int[]>(e.ExtraParams["productId"]);
            DeleteProduct(ids);
        }
    
        public bool DeleteProduct(int[] ProductIds)
        {
            bool returnVal = false;
            if (ProductIds != null)
            {
                try
                {
                    foreach (int ProductId in ProductIds)
                    {
                        Product toDelete = MyProducts.Find(p => p.ProductId == ProductId);
                        MyProducts.Remove(toDelete);
                    }
    
                    LoadProductsMenu();
    
                    mpProducts.SetSelectedIndex(mpProducts.Menu.Items.Count - 1);
                    pnlProductDetail.UpdateContent();
                    mpProducts.Menu.UpdateContent();
    
                    returnVal = true;
                }
                catch (Exception ex)
                {
                    Ext.Net.X.Msg.Show(new MessageBoxConfig
                    {
                        Title = "Error deleting product",
                        Message = ex.Message,
                        Icon = MessageBox.Icon.ERROR,
                        Buttons = MessageBox.Button.OK
                    });
                }
            }
    
            return returnVal;
        }
    
        [DirectMethod]
        public void LoadProductDetailForm(int productId)
        {
            ProductDetailForm pdf = new ProductDetailForm(productId);
            pnlProductDetail.Items.Clear();
            pnlProductDetail.Items.Add(pdf);
            pnlProductDetail.UpdateContent();
        }
    
        public class ProductDetailForm : global::Ext.Net.FormPanel
        {
            #region Properties
            public int ProductId { get; set; }
            #endregion
    
            #region Constructors
            public ProductDetailForm()
            {
            }
    
            public ProductDetailForm(int _ProductId)
            {
                this.ProductId = _ProductId;
            }
            #endregion
    
            #region Page Methods
            protected override void OnLoad(EventArgs e)
            {
                base.OnLoad(e);
                InitControls();
            }
    
            protected override void OnPreRender(EventArgs e)
            {
                base.OnPreRender(e);
            }
            #endregion
    
            #region Methods
            private void InitControls()
            {
                this.ID = "pnlOuterProductPanel";
                this.Header = false;
                this.Border = false;
                this.Layout = "FormLayout";
                this.Padding = 5;
    
                if (ProductId != 0)
                {
                    Product MyProduct = ((List<Product>)HttpContext.Current.Session["products"]).Find(p => p.ProductId == ProductId);
                    DisplayField df = new DisplayField();
                    df.ID = "df" + MyProduct.ProductId.ToString();
                    df.Text = "This is dummy information about the following product: " + MyProduct.Name;
                    this.Items.Add(df);
                }
                else
                {
                    DisplayField df = new DisplayField();
                    df.ID = "dfEmpty";
                    df.Text = "There are no products assigned to this group.";
                    this.Items.Add(df);
                }
            }
            #endregion
        }
    </script>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Testing</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <ext:ResourceManager ID="ResourceManager1" runat="server" Theme="Gray">
        </ext:ResourceManager>
        <script type="text/javascript">
            var menu_getSelectedId = function (m) {
                var selectedIds = [];
    
                var index = parseInt(m.getSelIndexField().getValue());
                var item;
                if (!isNaN(index)) {
                    item = m.menu.items.get(index);
                    selectedIds.push(item.productid);
                }
    
                return Ext.encode(selectedIds);
            }
            var menuItemClick = function (item) {
                var productId = item.productid;
    
                if (productId != 0) {
                    Ext.net.DirectMethods.LoadProductDetailForm(productId);
                }
            }
        </script>
                <ext:MenuPanel ID="mpProducts" runat="server" Selectable="true" SelectedIndex="0" Width="200">
                    <Menu ID="mItems" runat="server" ShowSeparator="false">
                        <Listeners>
                            <ItemClick Fn="menuItemClick" />
                        </Listeners>
                    </Menu>
                </ext:MenuPanel>
                <ext:Panel ID="pnlProductDetail" runat="server" Title="Product Info" AutoScroll="true">
                    <TopBar>
                        <ext:Toolbar ID="toolProduct" runat="server">
                            <Items>
                                <ext:ToolbarFill ID="ToolbarFill4" runat="server" />
                                <ext:Button ID="btnAddProduct" runat="server" Icon="Add" Text="Add">
                                </ext:Button>
                                <ext:Button ID="btnDeleteProduct" runat="server" Icon="Delete" Text="Delete Selected">
                                    <DirectEvents>
                                        <Click OnEvent="btnDeleteProduct_Click">
                                            <Confirmation ConfirmRequest="true" Message="Are you sure you want to delete the selected product?" />
                                            <ExtraParams>
                                                <ext:Parameter Name="productId" Value="menu_getSelectedId(#{mpProducts})" Mode="Raw">
                                                </ext:Parameter>
                                            </ExtraParams>
                                        </Click>
                                    </DirectEvents>
                                </ext:Button>
                            </Items>
                        </ext:Toolbar>
                    </TopBar>
                </ext:Panel>
        </form>
    </body>
    </html>
  8. #8
    Well, I can demonstrate that the server SetSelectedIndex works well.

    Example
    <%@ Page Language="C#" %>
     
    <%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
    
    <script runat="server">
        protected void Delete(object sender, DirectEventArgs e)
        {
            this.MenuPanel1.Menu.Remove("MenuItemTest");
            this.MenuPanel1.SetSelectedIndex(1);
        }
    </script>
     
    <!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>Ext.Net Example</title>
    </head>
    <body>
        <form runat="server">
            <ext:ResourceManager runat="server" />
            <ext:Button runat="server" Text="Delete" OnDirectClick="Delete" />
            <ext:MenuPanel ID="MenuPanel1" runat="server">
                <Menu runat="server">
                    <Items>
                        <ext:MenuItem Text="Item 1" />
                        <ext:MenuItem Text="Item 2" />
                        <ext:MenuItem ID="MenuItemTest" Text="Item 3" />
                    </Items>
                </Menu>
            </ext:MenuPanel>
        </form>
    </body>
    </html>
    Please provide your full test case like my one to copy/run. Please use some dummy data instead of database.
  9. #9
    Thanks for the good sample.

    Please see the working version.

    Example
    <%@ Page Language="C#" %>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
        public class Product
        {
            public Product() { }
     
            public int ProductId { get; set; }
            public string Name { get; set; }
        }
     
        public List<Product> MyProducts
        {
            get
            {
                if (Session["products"] == null)
                {
                    List<Product> products = new List<Product>();
                    products.Add(new Product() { ProductId = 1, Name = "Healthcare Benefit Savings" });
                    products.Add(new Product() { ProductId = 2, Name = "Care Package" });
                    Session["products"] = products;
                }
                return (List<Product>)Session["products"];
            }
        }
     
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack && !X.IsAjaxRequest)
            {
                LoadProductsMenu();
            }
        }
     
        private void LoadProductsMenu()
        {
            mpProducts.Menu.Items.Clear();
            pnlProductDetail.Items.Clear();
     
            MyProducts.ForEach(p =>
            {
                Ext.Net.MenuItem mi = new Ext.Net.MenuItem();
                mi.Text = p.Name;
                mi.CustomConfig.Add(new ConfigItem("productid", p.ProductId.ToString()));
     
                mpProducts.Menu.Items.Add(mi);
            });
    
            ProductDetailForm pdf;
            if (mpProducts.Menu.Items.Count > 0)
            {
                pdf = new ProductDetailForm(Convert.ToInt32(mpProducts.Menu.Items[0].CustomConfig[0].Value));
                pnlProductDetail.Items.Add(pdf);
            }
            else
            {
                Ext.Net.MenuItem mi = new Ext.Net.MenuItem();
                mi.Text = "No Products";
                mi.CustomConfig.Add(new ConfigItem("productid", "0"));
                mpProducts.Menu.Items.Add(mi);
     
                pdf = new ProductDetailForm(0);
                pnlProductDetail.Items.Add(pdf);
            }
    
            if (X.IsAjaxRequest)
            {
                mpProducts.Render();
                pdf.Render();  
            }
        }
     
        protected void btnDeleteProduct_Click(object sender, DirectEventArgs e)
        {
            int[] ids = JSON.Deserialize<int[]>(e.ExtraParams["productId"]);
            DeleteProduct(ids);
        }
     
        public bool DeleteProduct(int[] ProductIds)
        {
            bool returnVal = false;
            if (ProductIds != null)
            {
                try
                {
                    foreach (int ProductId in ProductIds)
                    {
                        Product toDelete = MyProducts.Find(p => p.ProductId == ProductId);
                        MyProducts.Remove(toDelete);
                    }
     
                    LoadProductsMenu();
    
                    mpProducts.SetSelectedIndex(mpProducts.Menu.Items.Count - 1);
     
                    returnVal = true;
                }
                catch (Exception ex)
                {
                    Ext.Net.X.Msg.Show(new MessageBoxConfig
                    {
                        Title = "Error deleting product",
                        Message = ex.Message,
                        Icon = MessageBox.Icon.ERROR,
                        Buttons = MessageBox.Button.OK
                    });
                }
            }
     
            return returnVal;
        }
     
        [DirectMethod]
        public void LoadProductDetailForm(int productId)
        {
            ProductDetailForm pdf = new ProductDetailForm(productId);
            pnlProductDetail.Items.Clear();
            pnlProductDetail.Items.Add(pdf);
            pdf.Render();
        }
     
        public class ProductDetailForm : global::Ext.Net.FormPanel
        {
            #region Properties
            public int ProductId { get; set; }
            #endregion
     
            #region Constructors
            public ProductDetailForm()
            {
            }
     
            public ProductDetailForm(int _ProductId)
            {
                this.ProductId = _ProductId;
            }
            #endregion
     
            #region Page Methods
            protected override void OnLoad(EventArgs e)
            {
                base.OnLoad(e);
                InitControls();
            }
     
            protected override void OnPreRender(EventArgs e)
            {
                base.OnPreRender(e);
            }
            #endregion
     
            #region Methods
            private void InitControls()
            {
                this.ID = "pnlOuterProductPanel";
                this.Header = false;
                this.Border = false;
                this.Layout = "FormLayout";
                this.Padding = 5;
     
                if (ProductId != 0)
                {
                    Product MyProduct = ((List<Product>)HttpContext.Current.Session["products"]).Find(p => p.ProductId == ProductId);
                    DisplayField df = new DisplayField();
                    df.ID = "df" + MyProduct.ProductId.ToString();
                    df.Text = "This is dummy information about the following product: " + MyProduct.Name;
                    this.Items.Add(df);
                }
                else
                {
                    DisplayField df = new DisplayField();
                    df.ID = "dfEmpty";
                    df.Text = "There are no products assigned to this group.";
                    this.Items.Add(df);
                }
            }
            #endregion
        }
    </script>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Ext.Net Example</title>
    
        <script type="text/javascript">
            var menu_getSelectedId = function (m) {
                var selectedIds = [];
     
                var index = parseInt(m.getSelIndexField().getValue());
                var item;
                if (!isNaN(index)) {
                    item = m.menu.items.get(index);
                    selectedIds.push(item.productid);
                }
     
                return Ext.encode(selectedIds);
            }
            var menuItemClick = function (item) {
                var productId = item.productid;
     
                if (productId != 0) {
                    Ext.net.DirectMethods.LoadProductDetailForm(productId);
                }
            }
        </script>
    </head>
    <body>
        <form runat="server">
            <ext:ResourceManager runat="server" />
            <ext:Container runat="server">
                <Items>
                    <ext:MenuPanel 
                        ID="mpProducts" 
                        runat="server" 
                        Selectable="true" 
                        SelectedIndex="0" 
                        Width="200">
                        <Menu 
                            runat="server" 
                            ShowSeparator="false">
                            <Listeners>
                                <ItemClick Fn="menuItemClick" />
                            </Listeners>
                        </Menu>
                    </ext:MenuPanel>
                </Items>
            </ext:Container>
            <ext:Panel 
                ID="pnlProductDetail" 
                runat="server" 
                Title="Product Info" 
                AutoScroll="true">
                <TopBar>
                    <ext:Toolbar runat="server">
                        <Items>
                            <ext:ToolbarFill runat="server" />
                            <ext:Button runat="server" Icon="Add" Text="Add" />
                            <ext:Button runat="server" Icon="Delete" Text="Delete Selected">
                                <DirectEvents>
                                    <Click OnEvent="btnDeleteProduct_Click">
                                        <Confirmation ConfirmRequest="true" Message="Are you sure you want to delete the selected product?" />
                                        <ExtraParams>
                                            <ext:Parameter 
                                                Name="productId" 
                                                Value="menu_getSelectedId(#{mpProducts})" 
                                                Mode="Raw" />
                                        </ExtraParams>
                                    </Click>
                                </DirectEvents>
                            </ext:Button>
                        </Items>
                    </ext:Toolbar>
                </TopBar>
            </ext:Panel>
        </form>
    </body>
    </html>

Similar Threads

  1. Replies: 15
    Last Post: Sep 12, 2012, 1:46 PM
  2. Replies: 1
    Last Post: May 11, 2012, 12:57 PM
  3. Replies: 6
    Last Post: Jul 28, 2011, 4:43 PM
  4. Gridpanel = Get Selected Row Index - Client Side
    By Tbaseflug in forum 1.x Help
    Replies: 1
    Last Post: Sep 15, 2009, 11:23 PM
  5. Replies: 2
    Last Post: Jun 25, 2009, 5:06 PM

Posting Permissions