I created a blog website using MVC patter but now i want to add a view count to the blogs using Database , how should i do
Blog View Count Using Asp.net
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
I created a blog website using MVC patter but now i want to add a view count to the blogs using Database , how should i do
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jignesh KumarRank #91 · 22.9K reputationPosted Dec 4, 2023, 2:08 AM EST
Hello Abhisek,
Please use below one,
Model :
// Blog.cs (Model) public class Blog { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public int ViewCount { get; set; } }Youe Database connection here I have taken Entity framework DBContext
// YourDbContext.cs public class YourDbContext : DbContext { public DbSet Blogs { get; set; } // Your other configurations... }Your MVC Controller,
// BlogController.cs (Controller) public class BlogController : Controller { private YourDbContext _context; public BlogController(YourDbContext context) { _context = context; } public ActionResult Details(int id) { var blog = _context.Blogs.Find(id); if (blog != null) { // Increment the view count blog.ViewCount++; _context.SaveChanges(); return View(blog); } return HttpNotFound(); } }MVC View :