I am trying to get a list of Categories and along with that list I want to show the number or Count of records that match the category. I have the Json in the controller. Before I just returned a list of categories with a foreach. But now would like to show the count also. I created an SQL View and to tie the Categories to posts and this is what is in my ViewModel
public class PostsInCategories
{
public int Id { get; set; }
public string Name { get; set; }
public string UrlSlug { get; set; }
}
Then in the Controller, which needs cleaned up, and UrlSlug added:
public ActionResult Category()
{
//List<CategoryViewModel> Category = new List<CategoryViewModel>();
//Category = db.Categories.Where(k => k.IsDelete != true).OrderByDescending(a => a.CreatedDate).ToList().Select(a => a.ToCategoryModel()).ToList();
var model = (from c in db.PostsInCategories
group c by c.Name into g
orderby g.Count() descending
select new
{
Cat = g.Key,
CountPosts = g.Count()
}).ToList();
//return PartialView(@"~/Views/Blog/Partials/Category.cshtml", Category);
return Json(new { result = model }, JsonRequestBehavior.AllowGet);
}
And my view needs to have this kind of styling and converted to except the json string:
@model IEnumerable<MyProject.Models.CategoryViewModel>
<ul class="list list-border angle-double-right">
@foreach (var item in Model)
{
<li>
<a href="/Blog/Category/@item.UrlSlug/@item.Id">
@Html.DisplayFor(modelItem => item.Name)
<span>(19)</span>
</a>
</li>
}
</ul>
My question is how do I present the list in the view and how do I add the UrlSlug to the string. The UrlSlug is for the category.
Thanks for your help!
CodePudding user response:
Pre-requisites: CategoryViewModel
class structure should look as below:
Model
public class CategoryViewModel
{
public int Id { get; set; }
public string Cat { get; set; }
public string UrlSlug { get; set; }
public int CountPosts { get; set; }
}
Controller
- To get
Id
andUrlSlug
, as the LINQ statement is groupedPostsInCategories
byname
, you need.First()
to get the first record ofId
andUrlSlug
ingroup
. - Seems you are using Razor with
@model
binding, then you have to returnView(model)
for the controller method.
public ActionResult Category()
{
var model = (from c in db.PostsInCategories
group c by c.Name into g
orderby g.Count() descending
select new CategoryViewModel
{
Cat = g.Key,
Id = g.First().Id,
UrlSlug = g.First().UrlSlug,
CountPosts = g.Count()
}).ToList();
return View(model);
}
View
@model IEnumerable<MyProject.Models.CategoryViewModel>
<ul class="list list-border angle-double-right">
@foreach (var item in Model)
{
<li>
<a href="/Blog/Category/@item.UrlSlug/@item.Id">
@Html.DisplayFor(modelItem => item.Cat)
<span>@item.CountPosts</span>
</a>
</li>
}
</ul>
Output