.net CRUD更新,net Core和cshtml

blmhpbnm  于 2023-05-02  发布在  .NET
关注(0)|答案(1)|浏览(413)

如果这是一个简单的问题,我提前道歉,我正在学习。net和我真的希望能够使一个更新功能,我已经创建了一个。net 6 MVC解决方案
我创建了一个CardsController:

public class CardsController : Controller {

        private readonly CardsContext _context;
        public CardsController(CardsContext context) {
            _context = context;
        }

        public IActionResult Index() {
            var cards = _context.Cards.ToList();
            return View(cards);
        }

        [HttpGet]
        public IActionResult Create() {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create([Bind("Title,Description,Stage,Tag")] CardsModel cardsModel) {
            if (ModelState.IsValid) {
                _context.Add(cardsModel);
                _context.SaveChanges();
                return RedirectToAction(nameof(Index));
            }
            return View(cardsModel);
        }

        [HttpGet]
        public IActionResult Update(int? id) {
            if (id == null) {
                return NotFound();
            }

            var cardsModel = _context.Cards.Find(id);
            if (cardsModel == null) {
                return NotFound();
            }

            return View(cardsModel);
        }

        [HttpPut]
        [ValidateAntiForgeryToken]
        public IActionResult Update(int id, [FromBody] CardsModel cardsModel) {

            if(id != cardsModel.id) {
                return NotFound();
            }

            if (ModelState.IsValid) {
                try {
                    _context.Update(cardsModel);
                    _context.SaveChanges();
                }
                catch (DbUpdateConcurrencyException) {
                    return NotFound();
                }
                return RedirectToAction(nameof(Index));
            }

            return View(cardsModel);

        }

        [HttpDelete]
        public ActionResult Delete(int? id)
        {
            
            if (id == null){
                return NotFound();
            }

            var cardsModel = _context.Cards.Find(id);

            if(cardsModel == null)
            {
                return NotFound();
            }

            _context.Cards.Remove(cardsModel);
            _context.SaveChanges();
            return RedirectToAction(nameof(Index));

        }

    }

我为我的行动创建了一条路线:

app.UseEndpoints(endpoints => {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Cards}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(
                    name: "Delete",
                    pattern: "Cards/Delete/{id?}",
                    defaults: new { controller = "Cards", action = "Delete" });
                endpoints.MapControllerRoute(
                    name: "Update",
                    pattern: "Cards/Update/{id?}",
                    defaults: new { controller = "Cards", action = "Update" });
            });

我在cshtml中创建了一个删除和更新的函数:

<script>
    function deleteCard(id) {
        fetch('/Cards/Delete/' + id, {
            method: 'Delete'
        })
            .then(response => {
                if (response.ok) {
                    alert('Success!');
                } else {
                    alert('Error.');
                }
            })
            .catch(error => {
                alert('Error.');
                console.error(error);
            });
    }

    function UpdateCard(id) {
        fetch(`/Cards/Update/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                id: id,
                Title: "UpdatedCard",
                Description: "UpdatedCard",
                Stage: 0,
                Tag: 0
            })
        })
            .then(response => {
                if (response.ok) {
                    // atualização bem-sucedida, redirecionar para a página inicial
                    window.location.href = '/Cards/Index';
                } else {
                    // atualização falhou, lidar com o erro
                    console.error('Error updating card.');
                }
            })
            .catch(error => {
                console.error(error);
            });
    }


</script>

当我在cshtml中调用UpdateCard函数时,我在控制台中得到两个错误:PUT https://localhost:44307/Cards/Update/9 net::ERR_ABORTED 400更新卡时出错。
注意:删除函数工作,你能看看我的简单代码,并指出错误可能在哪里?

ct2axkht

ct2axkht1#

由于您将ValidateAntiForgeryToken应用于Update操作,因此需要在请求中包含防伪令牌,如docs所示。在构建API时,建议使用授权来保护端点,请参阅e。例如,question,以了解有关详细信息。

相关问题