Xtremcool Xtremcool - 6 months ago 25
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

and I am retrieving all the images in another viewbag as

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>

I want to retrieve images from
on basis of
getting from

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"),
@foreach (var dr in ViewBag.tblProperty.Rows)
    var id = (int) dr["Id"];

        @foreach (var imgItem in imageList.Where(d=>d.ParentId== id))

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download