Pro ASP.net MVC 5:SportsStore Administration - productID返回0

时间:2016-07-09 09:17:41

标签: c# asp.net asp.net-mvc-5

我正面临SportStore示例的问题。 当我想编辑产品时,productID的值返回0,因此 创建了一个新产品。 为了确保没有拼写错误,我将我的文件与作者文件进行了比较,它们是100%匹配。

源代码下方:

  

EFProductRepository.cs

using SportsStore.Domain.Abstract;
using SportsStore.Domain.Entities;
using System.Collections.Generic;

namespace SportsStore.Domain.Concrete
{
    public class EFProductRepository : IProductRepository
    {
        private EFDbContext context = new EFDbContext();

        public IEnumerable<Product> Products
        {
            get { return context.Products; }
        }

        public void SaveProduct(Product product)
        {

            if (product.ProductID == 0)
            {
                context.Products.Add(product);
            }
            else
            {
                Product dbEntry = context.Products.Find(product.ProductID);
                if (dbEntry != null)
                {
                    dbEntry.Name = product.Name;
                    dbEntry.Description = product.Description;
                    dbEntry.Price = product.Price;
                    dbEntry.Category = product.Category;
                }
            }
            context.SaveChanges();
        }
    }
}
  

IProductRepository.cs

using System.Collections.Generic;
using SportsStore.Domain.Entities;

namespace SportsStore.Domain.Abstract
{
    public interface IProductRepository
    {
        IEnumerable<Product> Products { get; }

        void SaveProduct(Product product);
    }
}
  

AdminController.cs

using System.Linq;
using System.Web.Mvc;
using SportsStore.Domain.Abstract;
using SportsStore.Domain.Entities;

namespace SportsStore.WebUI.Controllers
{
    public class AdminController : Controller
    {
        private IProductRepository repository;

        public AdminController(IProductRepository repo)
        {
            repository = repo;
        }

        public ViewResult Index()
        {
            return View(repository.Products);
        }

        public ViewResult Edit(int productId)
        {
            Product product = repository.Products
                .FirstOrDefault(p => p.ProductID == productId);
            return View(product);
        }

        [HttpPost]
        public ActionResult Edit(Product product)
        {
            if (ModelState.IsValid)
            {
                repository.SaveProduct(product);
                TempData["message"] = string.Format("{0} has been saved", product.Name);
                return RedirectToAction("Index");
            } else
            {
                //there is something wrong with the data values
                return View(product);
            }
        }
    }
}
  

Product.cs

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace SportsStore.Domain.Entities
{
    public class Product
    {
        [HiddenInput(DisplayValue = false)]
        public int ProductID { get; set; }

        [Required(ErrorMessage = "Please enter a product name")]
        public string Name { get; set; }

        [DataType(DataType.MultilineText)]
        [Required(ErrorMessage = "Please enter a description")]
        public string Description { get; set; }

        [Required]
        [Range(0.01, double.MaxValue, ErrorMessage = "Please enter a positive price")]
        public decimal Price { get; set; }

        [Required(ErrorMessage = "Please specify a category")]
        public string Category { get; set; }
    }
}
  

Index.cshtml

@model IEnumerable<SportsStore.Domain.Entities.Product>

@{
    ViewBag.Title = "Admin: All Products";
    Layout = "~/Views/Shared/_AdminLayout.cshtml";
}

<div class="panel panel-default">

    <div class="panel-heading">
        <h3>All Products</h3>
    </div>
    <div class="panel-body">
        <table class="table table-striped table-condensed table-bordered">
            <tr>
                <th class="text-right">ID</th>
                <th>Name</th>
                <th class="text-right">Price</th>
                <th class="text-center">Actions</th>
            </tr>
            @foreach (var item in Model)
            {
                <tr>
                    <td class="text-right">@item.ProductID</td>
                    <td>@Html.ActionLink(item.Name, "Edit", new { item.ProductID })</td>
                    <td class="text-right">@item.Price.ToString("c")</td>
                    <td class="text-center">
                        @using (Html.BeginForm("Delete", "Admin"))
                        {
                            @Html.Hidden("ProductID", item.ProductID)
                            <input type="submit"
                                   class="btn btn-default btn-xs"
                                   value="Delete" />
                        }
                    </td>
                </tr>
            }
        </table>
    </div>
    <div class="panel-footer">
        @Html.ActionLink("Add a new product", "Create", null,
            new { @class = "btn btn-default" })
    </div>
</div>
  

Edit.cshtml

@model SportsStore.Domain.Entities.Product

@{
    ViewBag.Title = "Admin: Edit " + @Model.Name;
    Layout = "~/Views/Shared/_AdminLayout.cshtml";
}

<div class="panel">
    <div class="panel-heading">
        <h3>Edit @Model.Name</h3>
    </div>

    @using (Html.BeginForm("Edit", "Admin"))
    {
        <div class="panel-body">
            @foreach (var property in ViewData.ModelMetadata.Properties)
            {
                if (property.PropertyName != "ProductID")
                {
                    <div class="form-group">

                        <label>@(property.DisplayName ?? property.PropertyName)</label>
                        @if (property.PropertyName == "Description")
                        {
                            @Html.TextArea(property.PropertyName, null,
                                new { @class = "form-control", rows = 5 })
                        }
                        else
                        {
                            @Html.TextBox(property.PropertyName, null,
                                new { @class = "form-control" })
                        }
                        @Html.ValidationMessage(property.PropertyName)
                    </div>
                }
            }
        </div>

        <div class="panel-footer">
            <input type="submit" value="Save" class="btn btn-primary" />
            @Html.ActionLink("Cancel and return to List", "Index", null, new
       {
           @class = "btn btn-default"
       })
        </div>
    }
</div>

到目前为止我添加了两个断点:

1。 Edit.cshtml

div class="panel">
    <div class="panel-heading">
        <h3>Edit @Model.Name (@Model.ProductID)</h3>
    </div>

选择Edit for Item1(Kayak)后,Visual Studio将设置产品 类别正确(ProductID = 1),在视图本身中显示“编辑皮划艇(1)”这是正确的。

2。 AdminController.cs

repository.SaveProduct(product);

更改,例如Kayak的价格并点击保存

查看当地人(产品)以下结果:

- Category   : "Watersports"
- Description: "A boat for one person"
- Name       : "Kayak"
- Price      : "276.00"
- ProductID  : "0"

我不知道为什么没有正确设置productID(ProductID = 0),因为显然所有其他参数都设置正确。

我希望有人有个好主意并帮助我解决问题。 谢谢。

0 个答案:

没有答案