I am at very basic stage of asp.net MVC development. So sometimes I struggle with simple LINQ queries to work.
scenario-
I have A page that
I slightly renovated your code with Foreign key relations ship. This will save your from using two different queries to your database (like what you are doing now).
So if you Database Model looks like this -
Then you should have one viewmodel in your code in this way -
public class ImageViewModel
{
public string ImageId { get; set; }
public string ImageUrl { get; set; }
public List<string> Comments { get; set; }
}
And your controller action which will return all the results should be like this -
public class ListController : Controller
{
public ActionResult Index()
{
ImageViewModel model;
using (SampleEntities entities = new SampleEntities())
{
model = (from p in entities.Images
where p.ImageId == "1"
select new ImageViewModel()
{
ImageId = p.ImageId,
ImageUrl = p.ImageUrl,
Comments = p.ImageComments.Select(pa => pa.Comment).ToList()
}).FirstOrDefault();
}
return View(model);
}
}
Finally the view which will display all the Image results -
@model MVC.Controllers.ImageViewModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div>
<h4>ImageViewModel</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.ImageId)
</dt>
<dd>
@Html.DisplayFor(model => model.ImageId)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ImageUrl)
</dt>
<dd>
@Html.DisplayFor(model => model.ImageUrl)
</dd>
<br/>
@foreach (var item in Model.Comments)
{
@item <br/>
}
</dl>
</div>
Output would be -
Your cardComment
property is a list of strings; it needs to be iterated in order to be displayed. Replace:
<ol>
<li>
@item.cardComment
</li>
</ol>
with:
<ol>
@foreach (var singleComment in Model.cardComment)
{
<li>@singleComment </li>
}
</ol>