Ahmad Ahmad - 2 years ago 91
C# Question

Actionlink to another view (MVC)

i am working on my MVCOnlineShop Project , i have shown categories on homepage by creating a partial view

CategoryLayout.cshtml
:

@model IEnumerable<MVCOnlineShop.Models.Category>
@{
ViewBag.Title = "CategoryLayout";
}
<ul class="nav navbar-nav">
@foreach (var Category in Model)
{
<li>
@Html.ActionLink(Category.CategoryName,
"ProductList", new { Category = Category.CategoryName })
</li>

</ul>


and added this in
_Layout.cshtml
:

@Html.Partial("CategoryLayout")


now i want to press on any category on the home page , and it will take me to products in such category , i have created this partial view
ProductList.cshtml
:

@model MVCOnlineShop.Models.Category

@{
ViewBag.Title = "ProductList";
}
<ul>

@foreach (var Product in Model.Products)
{
<li>
@Html.ActionLink(Product.ProductName,
"Details", new { id = Product.CategoryID })
</li>
}
</ul>


and this is my
HomeController
:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCOnlineShop.Models;

namespace MVCOnlineShop.Controllers
{
public class HomeController : Controller
{
OnlineStoreEntities storeDB = new OnlineStoreEntities();
//
// GET: /Home/

public ActionResult Index()
{
var Categories = storeDB.Categories.ToList();
return View(Categories);
}
//
// GET: /Home/Browse
public ActionResult Browse(string Category)
{
// Retrieve Category and its Associated Products from database
var CategoryModel = storeDB.Categories.Include("Products")
.Single(g => g.CategoryName == Category);

return View(CategoryModel);
}
//
// GET: /Home/Details
public ActionResult Details(int id)
{
var Product = storeDB.Products.Find(id);

return View(Product);
}
//
// GET: /Home/Browse?Category=Games

public ActionResult CategoryLayout()
{
var Categories = storeDB.Categories.ToList();
return PartialView("CategoryLayout", Categories);
}

}
}


Question: how can i press on a category on the homepage , and this will take me to a page showing the products in this category, can you help me please , thanks!!

Answer Source

Here we go :

First your action link should be :

<li> 
@Html.ActionLink(Category.CategoryName, 
"ProductList", new { CategoryId = Category.CategoryName }) 
</li>

And then you have to add ProductList action in your controller like :

public ActionResult ProductList(int? CategoryId)
{
     Category objCategory = new Category();

     objCategory.Products = storeDB.Products.where(m => m.CategoryId == CategoryId).ToList();

  return PartialView("ProductList", objCategory);
}

And your Product partial view Should be :

@model MVCOnlineShop.Models.Category 

@{ 
ViewBag.Title = "ProductList"; 
} 
<ul> 

@foreach (var Product in Model.Products) 
{ 
<li> 
@Html.ActionLink(Product.ProductName, 
"Details", new { id = Product.CategoryID }) 
</li> 
} 
</ul>

Cheers !!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download