【问题标题】:How to add Product ID automatically in list in MVC如何在 MVC 的列表中自动添加产品 ID
【发布时间】:2021-10-10 11:20:38
【问题描述】:

我正在制作一个网站来显示产品列表。前三个产品是硬编码的,现在我想在列表中添加一个新产品。添加产品后,它的 ID 在列表中应为 4,但在添加和保存新产品后,它在列表中向我显示 0。

如图,添加新产品后可以看到产品ID为0。请给我一个解决方案,我怎样才能避免那个 0 并且列表应该相应地编号。

模型代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVC5ModelDemo.Models
{
    //model class
    public class Product
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public int OrderId { get; set; }
        public int Quantity { get; set; }

    }
}

控制器代码:

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

namespace MVC5ModelDemo.Controllers
{
    public class HomeController : Controller
    {
        private static List<Product> productList = new List<Product>
        {

            new Product() { ProductId = 01, ProductName = "C# Book", OrderId = 02, Quantity = 2 },
            new Product() { ProductId = 02, ProductName = "ASP.NET Book", OrderId = 02, Quantity = 2 },
            new Product() { ProductId = 03, ProductName = "ASP.NET CORE Book", OrderId = 02, Quantity = 2 }

        };

        public ActionResult Index()
        {
            return View(productList.OrderBy(s => s.ProductId).ToList());
        }

        public ActionResult AddProduct()
        {
            //get the product from list
            return View("Add");
        }

        [HttpPost]
        public ActionResult AddProduct(Product p)
        {
            productList.Add(p);
            return RedirectToAction("Index");
        }
    }


}

Add.cshtml 的代码:

@model MVC5ModelDemo.Models.Product

@{
    ViewBag.Title = "Add";
}

<h2>Add</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Product</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.ProductName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ProductName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ProductName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.OrderId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.OrderId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.OrderId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Quantity, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Quantity, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Add Product" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Index.cshtml 的代码:

@model IEnumerable<MVC5ModelDemo.Models.Product>

@{
    ViewBag.Title = "Index";
}
<h3>All Product List</h3>
<p align="right">
    <button type="button"
            id="AddButton"
            class="btn btn-primary"
           onclick="location.href='@Url.Action("AddProduct", "Home")'">
        Add Product

    </button>
</p>
<table border="1" class="table table-bordered table-responsive">
    <thead>
        <tr class="btn-primary">
            <th>Product ID</th>
            <th>Product Name</th>
            <th>Order ID</th>
            <th>Quantity</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.ProductId</td>
                <td>@item.ProductName</td>
                <td>@item.OrderId</td>
                <td>@item.Quantity</td>
                <td>@Html.ActionLink("Edit", "Edit","Home", new { i = item.ProductId },null)
                or 
                @Html.ActionLink("Delete", "Delete", new { i = item.ProductId },null)</td>
            </tr>

        }
    </tbody>
</table>  

P.S:我是 asp.net C# 的新手,任何帮助将不胜感激

【问题讨论】:

    标签: c# asp.net-mvc visual-studio


    【解决方案1】:

    在您的Add 方法中,您会得到一个Product p,其中ProductId 设置为0。然后您将此新产品添加到集合中,您的Index 方法返回按ProductId 排序的集合。这样一来,新项目将始终具有 ProductId0,并且始终首先出现。

    您可以检查有多少项目,并始终采用下一个可用的 ProductId 并将您的 Add 方法更改为:

    int nextProductId = productList.OrderBy(p => p.ProductId).Last().ProductId;
    p.ProductId = nextProductId + 1;
    productList.Add(p);
    

    您确实需要注意,虽然这可行,但多人同时使用并不安全。您最终可能会得到重复的 ProductId。 这就是为什么数据库通常会提供唯一 ID 并跟踪它们的原因。但是对于这个简单的场景,这应该可以工作。

    【讨论】:

    • 非常感谢,它帮助了。此应用程序仅用于学习目的。所以这就是为什么我一开始不使用数据库的原因。快速编辑:p.ProductId = nextProductId+1;
    猜你喜欢
    • 2018-05-10
    • 2022-11-24
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    相关资源
    最近更新 更多