我如何在 ASP.NET MVC 中更新我的数据库

How do i make an update to my database in ASP.NET MVC

我正在使用 ASP.NET MVC 制作一个网络应用程序,我正在尝试编辑我的对象列表。例如,如果我将产品添加到网站,然后单击该产品的编辑以更改奖品,我只会得到一个带有新奖品的新对象,而不是将奖品更改为产品。

所以问题是它没有更新产品,而是添加了一个新产品。

这是我的产品控制器的样子:

using auktioner_MarcusR91.Data;
using auktioner_MarcusR91.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace auktioner_MarcusR91.Controllers
{
    public class InventoryController : Controller
    {
        private readonly AppDbContext _db;

        public InventoryController(AppDbContext db)
        {
            _db = db;
        }
        public IActionResult Index()
        {
            IEnumerable<Inventory> objInventoryList = _db.Inventories;
            return View(objInventoryList);
        }

        //GET
        public IActionResult Create()
        {
            return View();
        }
        //Post
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Inventory inventory)
        {
            _db.Inventories.Add(inventory);
            _db.SaveChanges();
            return RedirectToAction("index");
        }

        //GET
        public IActionResult Edit(int? id)
        {
            if (id == 0 || id == 5) 
            {
                return NotFound();
            }
            var inventoryFromDb = _db.Inventories.Find(id);

            if (inventoryFromDb == null)
            {
                return NotFound();
            }
            return View(inventoryFromDb);
        }
        //Post
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(Inventory inventory)
        {
            if (ModelState.IsValid) 
            {
                _db.Inventories.Update(inventory);
                _db.SaveChanges();
                return RedirectToAction("index");
            }
            return View(inventory);
            
        }
    }
}

我认为我的控制器有问题。

然而,这也是我编辑产品时的看法:

@model Inventory

<form method = "post" asp-action = "Edit">
    <div class = "border p-3 mt-4">
        <div class = "row pb-2">
            <h2 class = "text-primary">Edit Inventory</h2>
            <hr />
        </div>
        <div class = "mb-3">
            <label asp-for ="inventoryName"></label>
            <input asp-for = "inventoryName" />
            <label asp-for ="finalPrize"></label>
            <input asp-for = "finalPrize" />
            <label asp-for ="inventoryDesc"></label>
            <input asp-for = "inventoryDesc" />
            <p>1 för "Transport</p>
            <p>2 för "Smycken"</p>
            <p>3 för "Hushåll"</p>
            <p>4 för "Dekoration"</p>
            <select asp-for = "categoryId">
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
            </select>
        </div>
        <button type = "submit" class = "btn btn-primary" width = "100px">Update</button>
        <a asp-controller = "Inventory" asp-action = "index" class = "btn btn-secondary" style = "width: 100px">Back to products</a> 
    </div>

</form>

您必须添加一个主键 inventoryId 作为隐藏输入,如果没有这个键,您的清单实例看起来就像一个新的 EF 实例。 并且由于您在操作中使用了 [ValidateAntiForgeryToken],因此将其添加以使用另一种形式语法查看

@using (Html.BeginForm("Edit", "Inventory", FormMethod.Post))
{
 @Html.AntiForgeryToken()
<input type="hidden" asp-for="inventoryId" value="@Model.inventoryId" />

....


  <button type = "submit" class = "btn btn-primary" width = "100px">Update</button>
<a asp-controller = "Inventory" asp-action = "index" class = "btn btn-secondary" style = "width: 100px">Back to products</a> 
    </div>
}

恕我直言,您的更新代码可能是这样的

if (ModelState.IsValid) 
{
 var inventoryFromDb = _db.Inventories.Find(inventory.inventoryId);
if (inventoryFromDb == null)
{
    return NotFound();
 }
    _db.Entry(inventoryFromDb).CurrentValues.SetValues(inventory);
   var result=  _db.SaveChanges();
}

您必须通过单击记录的更新按钮将您的记录 ID 发送到控制器。像这样:

<a class="btn btn-warning btn-sm btn-margin" asp-controller="ContextController" asp-action="UpdateAction" ***asp-route-id="@item.Id***">Update</a>

which @item 是模型发送到视图的对象。 行动将是:

[HttpGet]
public IActionResult UpdateAction(int id)
    {
        Model record = _Context.GetById(id);
        return View("UpdateFormPageOrModal",record);
    }

更新表单并单击视图数据的提交按钮后将发送到操作:

[HttpPost]
public IActionResult UpdateAction(Model record)
    {     
            var result = _Context.UpdateBy(record);
            ViewData["Result"] = result.Message;
            if (result.IsSucceeded)
            {
                _UnitOfWork.Save();
                return RedirectToAction("TheGridView");
            }
            return View("UpdateView",record);
     }

其中 UpdateBy() 方法应该是这样的:

public void UpdateBy(T entity)//entity is an object of the DbSet<Model>
        {
            var state = _Context.Entry(entity).State;
            if (state == EntityState.Detached)
            {
                _Context.Attach(entity);
            }
            _Context.Entry(entity).State = EntityState.Modified;
        }