0
votes

How can I load URL path from database from to view with foreign key "BAZ_ID"?

IMAGE_URL:

~/UploadImg/Untitled.png

Controller:

 public ActionResult Bazar()
    {
        WebEntities db = new WebEntities();
        var data = db.bazar.Include(c => c.images);
        return View(data.ToList());
    }

And view:

 <div class="col-sm-2">
            <img src= "@Url.Content(modelItem => item.images.Where(a => a.BAZ_ID == item.ID).Select(b => b.IMAGE_URL).FirstOrDefault())" width="150" height="150" />
        </div>

In view I get error:

Cannot convert lambda expression to type 'string' because it is not a delegate type

1
Remove the leading modelItem => . But your queries belong in the controller, not the view and you should be passing a view model that contains a property for the image url. - user3559349
FirstOrDefault() is not guaranteed to return an object that is not null. - Timothy Groote
@StephenMuecke consider adding you comment as answer - so many times I see your great answers and I can't "properly" upvote them ;-) - Paweł Hemperek

1 Answers

2
votes

The Url.Content method requires a string as the parameter, not a lambda expression.

You can change the code in you loop to (drop the leading modelItem =>)

<img src= "@Url.Content(item.images.Where(a => a.BAZ_ID == item.ID).Select(b => b.IMAGE_URL).FirstOrDefault())" ... />

However, queries belong in the controller, not the view, and your view model should contain a property (say) string ImageUrl which you populate in the controller, and then in the view

<img src= "@Url.Content(item.ImageUrl)" ... />