Martin Martin - 15 days ago 6x
C# Question

MVC View Image URL: Cannot convert lambda expression to string

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




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" />

In view I get error:

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


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)" ... />