ASP.NET Core中的Razor Pages与EF Core - 更新相关数据 - 8个中的7个
创始人
2024-11-12 02:30:07
0

以下是使用ASP.NET Core中的Razor Pages和EF Core进行数据更新的解决方法的示例代码:

  1. 在Razor Pages中创建一个Update.cshtml页面,用于显示要更新的数据和输入更新后的值。
@page
@model UpdateModel

Update Data

  1. 在Razor Pages中创建一个Update.cshtml.cs文件,用于处理数据更新的后端逻辑。
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

public class UpdateModel : PageModel
{
    private readonly ApplicationDbContext _dbContext;

    public UpdateModel(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    [BindProperty]
    public DataModel Data { get; set; }

    public async Task OnGetAsync(int id)
    {
        Data = await _dbContext.Data.FirstOrDefaultAsync(d => d.Id == id);

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

        return Page();
    }

    public async Task OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _dbContext.Attach(Data).State = EntityState.Modified;

        try
        {
            await _dbContext.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!_dbContext.Data.Any(d => d.Id == Data.Id))
            {
                return NotFound();
            }
            throw;
        }

        return RedirectToPage("./Index");
    }
}
  1. 创建一个DataModel类,用于表示要更新的数据。
public class DataModel
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public int Age { get; set; }
}

请注意,上述示例中的Update.cshtml页面和Update.cshtml.cs文件应位于同一个文件夹中,以便Razor Pages正确识别它们。另外,需要根据实际情况修改数据库上下文类(ApplicationDbContext)以及数据模型(DataModel)的定义。

相关内容

热门资讯

盘点一款!微乐自建房辅助工具神... 盘点一款!微乐自建房辅助工具神器,微乐自建房脚本免费入口(开挂自建房)教程1、任何微乐自建房辅助工具...
分享实测!微乐自建房辅助工具,... 分享实测!微乐自建房辅助工具,微乐小程序免费黑科技(开挂自建房)软件1、首先打开微乐自建房辅助工具辅...
推荐一款!微乐微信自建房辅助工... 推荐一款!微乐微信自建房辅助工具插件,微乐小程序免费黑科技(开挂自建房)插件1、任何微乐微信自建房辅...
实测揭晓!微乐自建房辅助工具插... 实测揭晓!微乐自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)攻略;所有人都在同一条线...
盘点一款!微乐小程序麻将自建房... 盘点一款!微乐小程序麻将自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)教程1、微乐小...
推荐十款!微乐自建房辅助工具脚... 推荐十款!微乐自建房辅助工具脚本,微乐小程序免费黑科技(开挂自建房)教程1、微乐自建房辅助工具脚本辅...
盘点几款!微乐自建房辅助工具免... 盘点几款!微乐自建房辅助工具免费app,微乐自建房脚本免费入口(开挂自建房)app1.微乐自建房辅助...
最新技巧!微信卡五星辅助器,微... 最新技巧!微信卡五星辅助器,微乐自建房脚本免费入口(开挂自建房)方法微信卡五星辅助器透视方法中分为三...
实操分享!微乐自建房辅助工具免... 实操分享!微乐自建房辅助工具免费app,微乐小程序免费黑科技(开挂自建房)软件1、进入游戏-大厅左侧...
技术分享!微信卡五星辅助器,微... 技术分享!微信卡五星辅助器,微乐自建房脚本免费入口(开挂自建房)工具1)微信卡五星辅助器有没有挂:进...