如何使用ASP.Net MVC将商品从商店添加到购物车?

时间:2017-05-05 02:16:15

标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-4

我正在尝试制作网上商店应用程序,在这种情况下,我使用视频游戏作为示例。我为一个名为VideoGame.cs的视频游戏制作了一个模型类,它位于我的ASP.NET MVC项目的Models文件夹中。这个类看起来像:

namespace VideoGameStore.Models
{
    public class VideoGame
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
    }

    public class VideoGameDBContext : DbContext
    {
        public DbSet<VideoGame> VideoGames { get; set; }
    }
}

我使用EF Scaffolding制作一个名为VideoGamesController.cs的控制器,位于我项目的Controllers文件夹中。我想过以这样一种方式使用这个控制器,即具有管理员角色的用户可以向该商店添加新的,删除和更新的视频游戏。这就是我的控制器的样子:

namespace VideoGameStore.Controllers
{
    public class VideoGamesController : Controller
    {
        private VideoGameDBContext db = new VideoGameDBContext();

        // GET: VideoGames
        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.TitleSortParm = String.IsNullOrEmpty(sortOrder) ? "title_desc" : "";
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

            if(searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            var videoGames = from v in db.VideoGames
                             select v;
            if(!String.IsNullOrEmpty(searchString))
            {
                videoGames = videoGames.Where(s => s.Title.Contains(searchString) || s.Description.Contains(searchString));
            }

            switch(sortOrder)
            {
                case "title_desc":
                    videoGames = videoGames.OrderByDescending(s => s.Title);
                    break;
                case "Date":
                    videoGames = videoGames.OrderBy(s => s.ReleaseDate);
                    break;
                case "date_desc":
                    videoGames = videoGames.OrderByDescending(s => s.ReleaseDate);
                    break;
                default:
                    videoGames = videoGames.OrderBy(s => s.Title);
                    break;
            }

            int pageSize = 20;
            int pageNumber = (page ?? 1);
            return View(videoGames.ToPagedList(pageNumber, pageSize));
        }

        // GET: VideoGames/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            VideoGame videoGame = db.VideoGames.Find(id);
            if (videoGame == null)
            {
                return HttpNotFound();
            }
            return View(videoGame);
        }


        [Authorize(Roles="Admin")]
        // GET: VideoGames/Create
        public ActionResult Create()
        {
            return View();
        }
        [Authorize(Roles="Admin")]
        // POST: VideoGames/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Title,ReleaseDate,Genre,Description,Price")] VideoGame videoGame)
        {
            if (ModelState.IsValid)
            {
                db.VideoGames.Add(videoGame);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(videoGame);
        }

        [Authorize(Roles="Admin")]
        // GET: VideoGames/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            VideoGame videoGame = db.VideoGames.Find(id);
            if (videoGame == null)
            {
                return HttpNotFound();
            }
            return View(videoGame);
        }

        [Authorize(Roles="Admin")]
        // POST: VideoGames/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Title,ReleaseDate,Genre,Description,Price")] VideoGame videoGame)
        {
            if (ModelState.IsValid)
            {
                db.Entry(videoGame).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(videoGame);
        }

        [Authorize(Roles="Admin")]
        // GET: VideoGames/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            VideoGame videoGame = db.VideoGames.Find(id);
            if (videoGame == null)
            {
                return HttpNotFound();
            }
            return View(videoGame);
        }

        [Authorize(Roles="Admin")]
        // POST: VideoGames/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            VideoGame videoGame = db.VideoGames.Find(id);
            db.VideoGames.Remove(videoGame);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

最后,我将拥有一个View,其中项目将向用户显示商店中可用的视频游戏集合(如果用户是管理员,则可以在此视图上管理集合)。名为Index.cshtml的视图位于Views/VideoGames文件夹中,如下所示:

@model PagedList.IPagedList<VideoGameStore.Models.VideoGame>
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />

@{
    ViewBag.Title = "Video Games Store";
}

<h2>Video Games Store</h2>

@if (User.Identity.IsAuthenticated)
{
    if (User.IsInRole("Admin"))
    {
        <p>
            @Html.ActionLink("Create New", "Create")
        </p>
    }
}

@using(Html.BeginForm("Index", "VideoGames", FormMethod.Get))
{
    <p>
        @Html.TextBox("searchString", ViewBag.CurrentFilter as string)
        <input type="submit" value="Search" />
    </p>
}

<div class="row">
    @foreach (var item in Model) {
        <div class="col-md-3">
            @Html.DisplayFor(modelItem => item.Title)<br />
            @Html.DisplayFor(modelItem => item.Genre)<br />
            &euro;@Html.DisplayFor(modelItem => item.Price)<br />
            @if (User.Identity.IsAuthenticated)
            {
                if(User.IsInRole("Admin"))
                {
                    @Html.ActionLink("Edit", "Edit", new { id = item.Id }) <text> | </text>
                }
            }
            @Html.ActionLink("Details", "Details", new { id=item.Id })
            @if (User.Identity.IsAuthenticated)
            {
                if (User.IsInRole("Admin"))
                {
                    <text> | </text> @Html.ActionLink("Delete", "Delete", new { id = item.Id })
                }
            }
            <br />
            @Html.ActionLink("Add to cart", "AddToCart", new { controller = "ShoppingCart", id = item.Id })
        </div>
    }
</div>
<div class="row">
    <div class="col-md-12">
        Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

        @Html.PagedListPager(Model, page => Url.Action("Index", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
    </div>
</div>

目前我想添加一些代码,以便用户点击@Html.ActionLink("Add to cart", "AddToCart", new { controller = "ShoppingCart", id = item.Id })后,用户就可以将所需的商品添加到购物车中。我想添加一个名为ShoppingCartController.cs的新控制器来处理购物车处理,这就是为什么我将它添加到视图中的ActionLink HTML帮助器。这就是ShoppingCartController.cs的样子:

namespace VideoGameStore.Controllers
{
    public class ShoppingCartController : Controller
    {
        // GET: ShoppingCart
        public ActionResult Index()
        {
            return View();
        }


        public ActionResult AddToCart(int Id)
        {
            //What code could I add here?
            return RedirectToAction("Index");
        }
    }
}

我一直在阅读使用MVC中的会话来制作购物车不是理想的解决方法。我是否必须将ShoppingCart模型添加到我的项目中并将购物车数据存储在数据库中(如果是这样,我怎么能看起来像这样)?我还读到我不希望用户在HTTP GET请求上存储数据,但我不希望用户必须发布他们的决定,将项目再次添加到不同页面上的购物车中。我怎样才能调整ShoppingCartController.cs

0 个答案:

没有答案