【问题标题】:Populating data from last row in form when creating a new entry创建新条目时从表单的最后一行填充数据
【发布时间】:2020-02-28 22:14:02
【问题描述】:

我有一个为 cmets 创建新数据条目的表单。创建全新的条目工作正常。但是,当我已经为我的实体创建了一个条目时,我想从表单中的最后一个条目中填充数据。

我已尝试修改 OnGet 操作以包含最后一个条目中的数据。我将 OnGet 代码从 Edit 视图复制到 Create 视图中。但是,如果我这样做,则不再显示创建页面。

我有以下型号:

    public class ProjectComment
    {
        public int Id { get; set; }

        public int? ProjectId { get; set; }
        public Project Project { get; set; }

        public int RAGStatusId { get; set; }
        public RAGStatus RAGStatus { get; set; }

        public string StatusComment { get; set; }
        public string EscalationComment { get; set; }
        public string GeneralComment { get; set; }
        public double? EOQ { get; set; }
        public DateTime LastUpdateDate { get; set; }
        public ProjectComment ()
        {
            this.LastUpdateDate = DateTime.UtcNow;
        }

创建表单Create.cshtml:

@page
@model SimpleProjectReporting.Pages.ClientDetails.CreateModel

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>ProjectComment</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="ProjectComment.ProjectId" class="control-label"></label>
                <select asp-for="ProjectComment.ProjectId" class="form-control" asp-items="ViewBag.ProjectId"><option value="" default="" selected="">-- Select --</option></select>
            </div>
            <div class="form-group">
                <label asp-for="ProjectComment.RAGStatusId" class="control-label"></label>
                <select asp-for="ProjectComment.RAGStatusId" class="form-control" asp-items="ViewBag.RAGStatusId"><option value="" default="" selected="">-- Select --</option></select>
            </div>
            <div class="form-group">
                <label asp-for="ProjectComment.StatusComment" class="control-label"></label>
                <input asp-for="ProjectComment.StatusComment" class="form-control" />
                <span asp-validation-for="ProjectComment.StatusComment" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ProjectComment.EOQ" class="control-label"></label>
                <input asp-for="ProjectComment.EOQ" class="form-control" />
                <span asp-validation-for="ProjectComment.EOQ" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

原来的 Create.cshtml.cs 动作:

        [BindProperty]
        public ProjectComment ProjectComment { get; set; }

        public IActionResult OnGet()
        {
            ViewData["ProjectId"] = new SelectList(_context.Project.Where(a => a.IsArchived == false), "Id", "ProjectName");
            ViewData["RAGStatusId"] = new SelectList(_context.RAGStatus.Where(a => a.IsActive == true), "Id", "RAGStatusName");
            return Page();
        }

        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            _context.ProjectComment.Add(ProjectComment);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        }

修改后的 Create.cshtml.cs OnGet 动作:

        public async Task<IActionResult> OnGetAsync(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            ProjectComment = await _context.ProjectComment
                .Include(p => p.Project)
                .Include(p => p.RAGStatus).FirstOrDefaultAsync(m => m.Id == id);

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

按照我的方式修改操作时,页面不再显示(404 错误)。 我想用数据库中最后一个条目的数据填充创建表单。如果没有评论,创建页面只会填充项目的名称。

【问题讨论】:

    标签: asp.net razor-pages actionresult


    【解决方案1】:

    我猜你没有将“id”参数发送到你的帖子操作。

    那么您能否尝试在您的form 标签下添加此行:

    <form method="post">
    <input type="hidden" id="ProjectComment.Id" name="id" value="ProjectComment.Id" />
    

    【讨论】:

    • 谢谢。这让我更进一步。但是,我现在收到错误“当 IDENTITY_INSERT 设置为 OFF 时,无法在表 'ProjectComment' 中插入标识列的显式值”。这是因为 Id 是自动生成的并且是唯一的。我怎样才能解决这个问题?
    • 那么您要向主键列插入数据吗?
    • 我只想填充其他字段。主键列应该是自动生成的。
    • 如果您试图达到数据库中最后一条记录的值,那么您应该改变您的方法。尝试使用以下命令查找最后一条记录: int max = db.ProjectComment .Max(p => p.Id);
    • 对不起,我对编码很陌生。我将在哪个文件中进行搜索(在 Create.cshtml 或 Create.cshtml.cs 中)?如何在 Create.cshtml 中显示最后一条评论的内容?能举个例子吗?
    【解决方案2】:

    您正在尝试访问ProjectComment 表的最后一条记录。 有不止一种方法可以找到数据表的最后一条记录。但让我们保持简单。

    您有一个基于整数的标识列,即自动增量。因此,您可以简单地使用以下方法来获取表中最后创建的数据。

    在您的OnGetAsync() 方法中:

    //maxId will be the maximum value of "Id" columns. Which means that the maximum value is the last recorded value.
    int maxId = _context.ProjectComment.Max(i => i.Id);
    
    //And this line will bring you the last recorded "ProjectComment" object.
    var projectComment = _context.ProjectComment.Find(maxId); 
    
    //You can assign it to your above 'ProjectComment' property if you want to.. 
    ProjectComment = projectComment 
    

    现在,由于您已在数据库中找到最后记录的数据,您可以使用该对象。

    【讨论】:

    • 您好 Burak,我终于有时间测试您的解决方案了。获取最后一条记录可以正常工作。但是,我需要添加 cmets 的项目的最后一条记录。所以我需要一个额外的约束:显示评论的项目(ProjectId)的最后一个 ProjectComment。当我从索引页面导航时,如何添加该约束,该页面列出了按客户分组的所有项目的所有 cmets?
    【解决方案3】:

    首先,感谢 Burak 提供上述解决方案,当您想要显示表格中的最后一行时,该解决方案有效。这帮助我通过使用相同的方法并根据记录的 ID 查找记录来解决我的问题。 我已将 Create.cshtml.cs 文件中的代码修改如下:

            public async Task<IActionResult> OnGetAsync(int? id, int projectid)
            {
                //This will find the "ProjectComment" object.
                var projectComment = _context.ProjectComment.Find(id);
    
                //This will display the 'ProjectComment' on the page 
                ProjectComment = projectComment;
                if (id == null)
                {
                    ProjectComment = projectComment; 
    
                    ViewData["ProjectId"] = new SelectList(_context.Project, "Id", "ProjectName", projectid);
    
    
                    return Page();
                }
                ViewData["ProjectId"] = new SelectList(_context.Project, "Id", "ProjectName");
                return Page();
            }
    
    

    当还没有评论创建时,我正在使用int projectid 填充项目的下拉菜单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-08
      相关资源
      最近更新 更多