Question

I have a numerical "badge" value that I'm trying to display on a menu in my MVC 5.1 app.

<span id="myBadge" class="badge menu-badge">@SessionData.MyCount</span>

I have a SessionData class so I don't have to pass around magic strings.

public class SessionData
{
    const string MyCountKey = "MyCount";

    public static int MyCount
    {
        get { return HttpContext.Current.Session[MyCountKey] != null ? (int)HttpContext.Current.Session[MyCountKey] : 0; }
        set { HttpContext.Current.Session[MyCountKey] = value; }
    }
}

The badge is initially populated from a base controller which performs a database call.

SessionData.MyCount = CountThingsFromDatabase();

I use javascript & jquery on the front-end as users modify data. If the count reaches 0, a jquery command hides the "0" badge.

function setBadgeValue(badgeName, count) {
  $(badgeName).html(count);
  count > 0 ? $(badgeName).show() : $(badgeName).hide();
}

All of this works fine with one exception. When the controller retrieves a count of "0", I'd like to hide the badge from the view in the same manner as the jquery show/hide commands. The front-end jquery piece works wonderfully, but I'm unsure of how to accomplish the same effect from the controller side of things.

Any help would be greatly appreciated.

Update 1:

The views I have utilize Telerik/Kendo objects. This is from a view which displays a Kendo grid. Each grid row has a button that is tied to this method. I'm not sure it would help to post the entire view/controller since most of it is Kendo related.

function addToCart(e) {
  // Get the grid data
  var grid = $("#Grid").data("kendoGrid");
  var dataItem = grid.dataItem(grid.select());

  // Add item to the cart
  $.ajax({
    url: 'Search/AddCart',
    data: { itemId: dataItem.ItemId },
    success: function () {
      $('_MyBadge').html();
      $('_Layout').html();

      // Update the count
      setBadgeValue("#myBadge", 1);
    },
    error: function (xmlHttpRequest, textStatus, errorThrown) {
      alert('Failed to add item #' + dataItem.itemId + ' to your cart.\nStatus: ' + textStatus + '\nError: ' + errorThrown);
    }
  });
}
Was it helpful?

Solution 2

No need to use the controller in any way, just hide your badge initially in the view if your count is zero.

<span id="myBadge" class="badge menu-badge" style="display: @(SessionData.MyCount > 0 ? "block" : "none");">@SessionData.MyCount</span>

OTHER TIPS

How about doing this on the view?

@if (SessionData.MyCount == 0)
{
    <span id="myBadge" class="badge menu-badge" style="display: none;">@SessionData.MyCount</span>
}
else
{
    <span id="myBadge" class="badge menu-badge">@SessionData.MyCount</span>
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top