ASP.NET CORE MVC CRUD 操作创建表单不再起作用

问题描述

我目前正在处理网站的 CRUD 操作。在附加的图片上,您可以看到我使用创建表单有两个目的。 1. 创建用户 2. 编辑用户。我的查询做得很好,但是当我添加一个隐藏的 id 来让某个用户进行编辑时。我不能再按创建用户了,因为我在图 1 中传递了一段代码。(我选择的行)

但是当我删除这段代码时,我可以创建一个用户,但是当我在删除这段代码时尝试编辑用户时,它只会编辑用户,然后使用编辑后的内容创建一个新用户。有谁知道如何解决这个问题?

附言我截取了控制器和出错的代码片段。

亲切的问候,

SEM

[出错的代码][1] [用户控制器][2] [用户 控制器][3] [数据传输对象][4] [CreateOrUpdate 查询/函数][5]

[1]:https://i.stack.imgur.com/5XxDe.jpg [2]: https://i.stack.imgur.com/s5pqh.jpg [3]: https://i.stack.imgur.com/2vLXM.jpg [4]: https://i.stack.imgur.com/R2OBn.jpg [5]: https://i.stack.imgur.com/ADyv5.jpg

解决方法

根据您的屏幕截图,您正在从 UI 调用相同的操作方法,在这种情况下,您需要验证操作方法中的 id 以查看它是否有效,然后进行更新,否则将添加。第一次您的页面加载 id 为空的场景,如果您加载第二次,它将具有 id 并且您可以用于编辑。

希望这能解决您的问题?

,

首先,您可以使用上方工具栏中的“{}”复制您的代码,这样其他人可以更方便地测试您的代码。

但是当我在删除这段代码时尝试编辑用户时,它只会编辑用户,然后使用编辑后的内容创建一个新用户。

您可以检查数据库中是否存在传递的模型,如果 id 存在,则创建一个,如果没有,则删除旧的并创建新的。

这是一个使用linq的演示,你可以检查逻辑并将我的代码修改为你的:

public async Task<IActionResult> ProcessCreate(UsersDto user)
    {
        if (!_context.UsersDtos.Any(x => x.Id == user.Id))  //if not exist,create one directly
        {
            _context.Add(user);
            await _context.SaveChangesAsync();
        }
        else {               //else,delete old one and create new one       
            var therow = _context.UsersDtos.Where(x => x.Id == user.Id).FirstOrDefault();
            _context.Remove(therow);
            _context.Add(user);
            await _context.SaveChangesAsync();
        }          
        return RedirectToAction("Index");
    }

在 Create.cshtml 中,您可以显示 id:

<form method="post" asp-action="ProcessCreate">
<div class="form-group" hidden>
    <label asp-for="Id" class="control-label"></label>
    <input asp-for="Id" class="form-control" />
    <span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group">
    <label asp-for="First_name" class="control-label"></label>
    <input asp-for="First_name" class="form-control" />
    <span asp-validation-for="First_name" class="text-danger"></span>
</div>
//.......
<div class="form-group">
    <input type="submit" value="CreateOrEdit" class="btn btn-primary" />
</div>

结果:

enter image description here