1

I´m tryin to make a query to receive all data in my database to show it in my view.

but it´s not working. i can´t figured it out what is going on because i don´t get any error.

anybody can help with this pls?

thanks in advance

Controller:

public ActionResult Details(int id = 0)
            {
                Persons p= db.persons.Find(id);

                var query = from a in db.images
                            where a.Id_Person== id
                            select a.FileName;
                ViewBag.ImgRev= query;

                if (mag == null)
                {
                    return HttpNotFound();
                }

                return View(p);
            }

View:

@foreach (var p in ViewBag.ImgRev)
        { 
          <div>
            <img src="~/Files/" + @p /></div>
        }
2
  • 1
    have you debugged and seen that there is data? Commented Sep 3, 2013 at 15:43
  • have check it.. its null.. what do i wrong? i miss something Commented Sep 3, 2013 at 15:45

1 Answer 1

1

The linq statement will not have evaluated before it is assigned to the ViewBag.

Try:

Controller:

ViewBag.ImgRev = query.ToList();

View:

@ {
    var imgList = ViewBag.ImgRev as IEnumerable<string>;
}

@foreach (var p in imgList)
{ 
    <div><img src="~/Files/" + @p /></div>
}

Alternative using ViewModel:

public class SomePageViewModel
{
    public Persons Persons { get; set; }
    public IEnumerable<string> Files { get; set; }
}

Controller:

...
var model = new SomePageViewModel { Persons = p, Files = query.ToList() };
return model;

View:

@foreach (var file in Model.Files)
{ 
    <div><img src="~/Files/" + @file /></div>
}
Sign up to request clarification or add additional context in comments.

6 Comments

romoku where come your <Image> from?
I guessed the class name.
i try your code but i get now this error: Object reference not set to an instance of an object. :Breakpoint foreach
i have set a breakpont in the controller and have check the query and still are null....
Make sure it's connected to the database.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.