【问题标题】:How do i make an update to my database in ASP.NET MVC如何在 ASP.NET MVC 中更新我的数据库
【发布时间】:2022-01-04 18:40:55
【问题描述】:

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

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

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

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>

【问题讨论】:

    标签: c# asp.net .net asp.net-mvc model-view-controller


    【解决方案1】:

    您必须添加主键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();
    }
    

    【讨论】:

    • 我应该把&lt;input type="hidden" 放在哪里?
    • @MarcusRosberg 表单内的任何地方
    • 我尝试了所有这些都没有任何运气
    • @MarcusRosberg 我更新了我的代码,再试一次
    【解决方案2】:

    您必须通过单击记录的更新按钮将记录 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;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      • 2015-04-20
      • 1970-01-01
      相关资源
      最近更新 更多