Search code examples
c#asp.net-mvcviewbag

How do I find the value of a ViewBag variable list item in C#


I have a case where I am loading a combobox based on a viewbag where it is populated by a select list

So the selectlist is populated via this code

private SelectList GetBranches(int? selected = null)
{
    IPracticeRepository rep = db.GetPracticeRepository();

    var curPracticeId = GetUser()?.PracticeId ?? 0;
    var branches = rep.GetById(curPracticeId).Branches;
    var selectList = new List<SelectListItem>();
    if (selected == null) selectList.Add(new SelectListItem() { Selected = true, Text = "", Value = "" });
    foreach (var item in branches)
    {
        if (item.CanCollectReceipts)
            selectList.Add(new SelectListItem() { Value = item.Id.ToString(), Text = item.Name, Selected = selected == item.Id });
    }
    if (selectList.Count == 0) selectList.Add(new SelectListItem() { Selected = true, Text = "", Value = "" });

    return new SelectList(selectList, "Value", "Text");
}
...

ViewBag.Branches = GetBranches(invoice.Visit.Branch.Id)

I then want to set a variable which will hide or show the combo box based on whether the first value is "" as set when the count is 0.

if (ViewBag.Branches == "")
{
    setSite = false;
}
else
{
    setSite = true;
}
ViewBag.Setsite = setSite;

So obviously the above code is not working but I am trying to figure out how do I find the value of that first value in the viewbag so I can set my variable.


Solution

  • if (((SelectList)ViewBag.Branches).First().Value == "")
    

    Although, if you are still on the controller side, then it's probably cleaner to

    var the_list = GetBranches(invoice.Visit.Branch.Id); // Guarantees at least 1 element in the list
    
    ViewBag.Branches = the_list;
    if (the_list.First().Value == "")
    {
      ...
    }
    

    Although still, if you are still on the controller side, you probably don't want to save setSite in the bag in the first place, given that it's strictly linked to the contents of the list. So you probably should move that part to the view:

    @{
        bool setSite = (((SelectList)ViewBag.Branches).First().Value != "";
    }
    
    // using setSite in the markup