Reputation: 1031
I have this code in my controller:
public ActionResult Index()
{
var announcementCat = (from p in db.announcements
join f in db.announcementsCategories
on p.kind equals f.ann_kind
select new
{
kindtext = f.ann_kindtext,
}).ToList()
.Select(x => new announcements()
{
kind = x.ann_kindtext
});
return View(db.announcements.OrderByDescending(announcements=> announcements.Pubdate).ToList());
}
And this is what I try in my View
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Pubdate)
</td>
<td>
@ViewBag.announcementCat
</td>
<td>
@Html.DisplayFor(modelItem => item.title)
</td>
</tr>
}
</table>
What I am trying is to bring the announcement
category and not the id
. But my code doesn't return anything and I don't get any errors. It brings all the data except the announcement
category which is the kindtext
field.
EDIT My 1st model
public class announcements
{
[Key]
[Display(Name = "ID")]
public int ann_ID { get; set; }
[Display(Name = "Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime Pubdate { get; set; }
[Display(Name = "Category")]
public int kind { get; set; }
[Display(Name = "Title")]
public String title { get; set; }
}
}
My 2nd model
public class announcementsCategories
{
[Key]
[Display(Name = "category ID")]
public int ann_kind { get; set; }
[Display(Name = "category description")]
public String ann_kindtext { get; set; }
}
Upvotes: 0
Views: 84
Reputation:
Start by creating a view model to represent what you want to display in the view
public class AnouncementVM
{
public string Title { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}")]
public DateTime Date { get; set; }
public string Category { get; set; }
}
Then in the GET method, project your query into the view model
public ActionResult Index()
{
var data = (from p in db.announcements
join f in db.announcementsCategories
on p.ann_ID equals f.ann_kind // note I think this needs to be - on p.kind equals f.ann_kind
select new AnouncementVM
{
Title = p.title,
Date = p.Pubdate,
Category = f.ann_kindtext
}).ToList();
return View(data.OrderByDescending(x => x.Date);
}
And in the view
@model IEnumerable<AnouncementVM>
....
@foreach(var item in Model)
{
<tr>
<td>@Html.DisplayFor(m => item.Date)</td>
<td>@Html.DisplayFor(m => item.Category)</td>
<td>@Html.DisplayFor(m => item.Title)</td>
</tr>
}
Upvotes: 1
Reputation: 39966
Because you've missed to return the announcementCat
to the view. You should return the join result like this:
ViewBag.announcementCatcode = announcementCat;
Then in the View
:
@foreach (var item in ((List<string>)ViewBag.announcementCatcode))
{
@item
}
Upvotes: 1