chris
chris

Reputation: 561

Is there a way to search for an item in a ViewBag?

I have a ViewBag.People made up from a View;

 var query = db.Vw_INTERACTPEOPLE.Select(p => new { p.PersonID, p.Fullname });
 ViewBag.People = new SelectList(query.AsEnumerable(), "PersonID", "FullName");

Which all works fine, but in my view I have another model populating a table, and one of the items is populates is an JobcontactID (textbox) which links to the PersonID (i didnt design the database). So I want to search the viewbag for the ID and rather than displaying it I want to display the persons Fullname, so is there any viewbag search functionality?

Upvotes: 1

Views: 4498

Answers (2)

moribvndvs
moribvndvs

Reputation: 42497

ViewBag is just a dynamic wrapper around ViewData (which allows the property invoked at runtime to become the key which will be used to look up the value in ViewData). You can query ViewData like this:

SelectList peopleSelectList = (from pair in ViewData
                               where pair.Key == "People"
                               select pair.Value);

Update So you wish to query the select list itself?

Here's a function defined in the razor view:

@functions {
    public string FindPersonName(string id)
    {
        return (from item in ViewBag.People as SelectList
                where item.Value == id
                select item.Value).FirstOrDefault();
    }
}

@functions.FindPersonName(jobContactId)

Upvotes: 2

Yusubov
Yusubov

Reputation: 5843

I would suggest to pass that information in your ViewModel. It will keep it clean and maintainable in long run. Here is a good post: Use ViewModels to manage data & organize code in ASP.NET MVC applications

Upvotes: 8

Related Questions