I am working on a e-shop in ASP.NET MVC, and I just made the listing of product the way I figured out this night. Is it correct? Or should I make it differently? How?
So this is my Product controller, used for displaying the products from Db.
using WebShop.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebShop.Controllers
{
public class ProductController : Controller
{
private WebShopEntities db = new WebShopEntities();
public ActionResult Category(int? id)
{
int pid = id == null ? 1 : (int)id; //if requested id is null, set is as 1
if (db.Categories.Find(pid) == null) //if category does not exist, return Error
return View("Error");
var model = db.Categories.Find(pid).Products.ToList(); //return list of projects in requested category
return View(model);
}
}
}
This is the Category View.
@using WebShop.Models
@{
ViewBag.Title = "Category";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="vert-offset-top-2">
<div class="list-group col-sm-3">
@Html.Partial("Partial/_PartialCategoryMenu") //display partial view for category menu
</div>
<div class="row">
@foreach(Product p in Model)
{
@Html.Partial("Partial/_PartialProduct", p) //display partial view
}
</div>
</div>
These are partial Views, which are self-explanatory I hope. Category partial view
@using WebShop.Models
@using (var db = new WebShopEntities()) {
foreach (var category in db.Categories)
{
<a href="@Url.Action("Category","Product", new {id = category.id})" class="list-group-item">@category.name</a>
}
}
Product partial view
<div class="vert-offset-bottom-1 col-sm-3">
<div class="thumbnail">
<img src="" class="img-responsive" alt="Product image">
<div class="caption">
<h3>@Model.name</h3>
<h4>@Model.price €</h4>
<p>@Model.description</p>
<p><a href="#" class="btn btn-primary" role="button">To Cart</a> <a href="@Url.Action("Details", "Product", new {id = @Model.id})" class="btn btn-default" role="button">Details</a></p>
</div>
</div>
</div>