Search code examples
c#devexpressdevexpress-mvcdevexpress-gridcontrol

How to show or hide and element when using Devexpress Cardview based on table column value


I am using Devexpress's CardView and I am doing my binding to the database like this:

    var cardView = Html.DevExpress().CardView(settings =>
    {
      settings.Name = "MyCardView";
    }

    @cardView.BindToEF(string.Empty, string.Empty, (s, e) =>
    {
      e.QueryableSource = Helper.CustomerData();
    }).GetHtml()

Now I can add a link to the top of the card by doing this:

    var cardView = Html.DevExpress().CardView(settings =>
    {
      settings.Name = "MyCardView";
      settings.CardLayoutProperties.Items.AddGroupItem(g =>
      {
          g.ColSpan = 1;
          g.ShowCaption = DefaultBoolean.False;
          g.GroupBoxDecoration = GroupBoxDecoration.None;

          var cmdLayoutItem = new CardViewCommandLayoutItem();
          cmdLayoutItem.HorizontalAlign = FormLayoutHorizontalAlign.Right;

          var publicUrlButton = new CardViewCustomCommandButton();
          publicUrlButton.ID = "Link123";
          publicUrlButton.Text = "My Funny Url";

          cmdLayoutItem.CustomButtons.Add(publicUrlButton);
          g.Items.Add(cmdLayoutItem);
        });

        settings.Columns.Add(c =>
        {
            c.FieldName = "Id";
            c.Caption = "Id";
            c.ReadOnly = true;
            c.Visible = false;
        });

        settings.Columns.Add(c =>
        {
            c.FieldName = "IsOpen";
            c.Caption = "IsOpen";
            c.ReadOnly = true;
            c.Visible = false;
        });
    }

    @cardView.BindToEF(string.Empty, string.Empty, (s, e) =>
    {
      e.QueryableSource = Helper.CustomerData();
    }).GetHtml()

The Helper.CustomerData() returns an IQueryable<CustomerData>. Now imagine my table CustomerData has a column called IsOpen. How can I show the publicUrlButton only when the value of IsOpen is true?


Solution

  • Finally found the solution after hours digging. Basically you can use the following event to control the behaviour:

            settings.CustomButtonInitialize = (s, e) =>
            {
                var cv = s as MVCxCardView;
                if (cv == null)
                {
                    return;
                }
    
                var isOpen = cv.GetCardValues(e.VisibleIndex, "IsOpen");
                if (!isOpen)
                {
                    if (e.ButtonID == "Link123")
                    {
                        e.Visible = DefaultBoolean.False;
                    }
                }
            };