Xtremcool Xtremcool - 28 days ago 7
ASP.NET (C#) Question

Possible to retrieve data from viewbag with where condition

I am trying to retrieve images on basis of property id.

What I am doing is getting all the property text data in one view bag says

ViewBag.tblProperty
and I am retrieving all the images in another viewbag as
ViewBag.tblImages
.

This is my code:

@foreach (System.Data.DataRow dr in ViewBag.tblProperty.Rows)
{
<ul class="popup-gallery-@dr["PropertyID"] bxslider-@dr["PropertyID"]">
@foreach (System.Data.DataRow dr in ViewBag.tblimages.where(@dr["PropertyID"]).Rows)
{
<li><a href="@dr["FileName"]"><img src="@dr["FileName"]" /></a></li>
}
</ul>
}


I want to retrieve images from
ViewBag.tblImages
on basis of
PropertyID
getting from
ViewBag.tblProperty
.

How can I do so?

Answer Source

ViewBag is dictionary which stores item as dynamic type. So you need to first convert that to a DataTable and can use AsEnumerable method to convert your data table to a list of anonymous objects which you can use later with a Where clause

Assuming your tblImages has an Id,FileName and ParentId properties

@{
    var imgsDt = ViewBag.tblimages as DataTable;
    var imageList = imgsDt.AsEnumerable().Select(t => new
    {
        Id = t.Field<int>("Id"),
        FileName= t.Field<string>("FileName"),
        ParentId = t.Field<int>("ParentId"),
    }).ToList();
}
@foreach (var dr in ViewBag.tblProperty.Rows)
{
    var id = (int) dr["Id"];

    <div>
        <span>@dr["Name"]</span>
        @foreach (var imgItem in imageList.Where(d=>d.ParentId== id))
        {
            <div>@imgItem.FileName</div>
        }
    </div>
}

You need to add @using System.Data to the top of your view.

For simplicity, i updated the markup to just print the name/property values inside a div. you can update that part to your markup (ul-li)

While this might fix the issue, I strongly recommend you to not use DataTables with ViewBag to transfer data. The code is going to be hard to maintain. I suggest you create a view model class and load the data to the view model in your action method and send the view model to the view. This way your view will not have any idea what sort of data access you are using and it is going to be very clean and readable.

You can use SqlDataReader if you are writing custom ado.net code. Create a POCO class representing your entities and assign to that. There are tons of samples on internet about that.