首页 > 解决方案 > 从集合中删除对象时,.net core 2.2 razor 页面视图无法正确更新

问题描述

对 asp .net 核心来说相当新,但试图创建一个简洁的 crud 网格,我不明白为什么当我使用删除后处理程序从列表中删除某一行时,它总是返回删除最后一行的列表而不是一个被选中。

调试 OnPostDelete 显示它从列表中删除了正确的行。
测试 RemoveAt 在 onget() 中按预期工作,但在 onpostdelete 中没有。

下面是我在cs文件后面的大部分代码

 using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.Extensions.Configuration;
    using RazorPagesExample.Entity;
    using System.Data.SqlClient;
    using Dapper;

    namespace RazorPagesExample.Pages
    {

        public class multirowformModel : PageModel 
        {

            public class Proddaplocal
            {
                public int? Id { get; set; }
                public string Name { get; set; }
                public string Model { get; set; }
                public int Price { get; set; }
               public string Country { get; set; }
            }        

            [BindProperty]        
            public List<Proddaplocal> products { get; set; }        

            IConfiguration config;
            string connectionString;
            public multirowformModel(IConfiguration configuration)
            {
                if (configuration != null)
                {
                    config = configuration;
                    connectionString = config.GetSection("ConnectionStrings").GetSection("ProductContext").Value;
                }            
            }
            public void OnGet()
            {            
                using (var con = new SqlConnection(connectionString))
                {
                    try
                    {
                        con.Open();
                        var query = "SELECT Id,Name,Model,Price,Country FROM Product";
                        products = con.Query<Proddaplocal>(query).ToList();                 
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        con.Close();
                    }
                }
            }

            public IActionResult OnPostDelete(int? id)
            {

                if (ModelState.IsValid)
                {
                    if (id == null)
                    {
                        return NotFound();
                    }
                    int delid = id ?? 0;
                    products.RemoveAt(delid);

                }

                return Page();
           }
       }
   }

下面是我的剃刀观点

  @page
    @model RazorPagesExample.Pages.multirowformModel
    @{
    ViewData["Title"] = "form table";
    }

    <h1>datatables</h1>

    <form id=multiform method="post" >
    <div class="table-responsive" style="max-width:800px">
        <table class="table table-sm">
            <thead class="thead-dark">
                <tr>
                    <th scope="col" style="width:30%;min-width:100px">
                        @Html.DisplayNameFor(model => model.products[0].Name)
                    </th>
                    <th scope="col" style="min-width:100px">
                        @Html.DisplayNameFor(model => model.products[0].Model)
                    </th>
                    <th scope="col" style="width:15%; min-width:100px">
                        @Html.DisplayNameFor(model => model.products[0].Price)
                    </th>
                    <th scope="col" style="min-width:100px">
                        @Html.DisplayNameFor(model => model.products[0].Country)
                    </th>
                    <th scope="col" style="min-width:50px">Actions</th>
                </tr>
            </thead>

            <tbody>
                @for (int i = 0; i < Model.products.Count; i++)
                {
                    <tr>
                        <td>
                            <input asp-for="@Model.products[i].Id" type="hidden" />
                            <input asp-for="@Model.products[i].Name" class="form-control" />
                        </td>
                        <td>
                            <input asp-for="@Model.products[i].Model" class="form-control" />
                        </td>
                        <td>
                            <input asp-for="@Model.products[i].Price" class="form-control" />
                        </td>
                        <td>
                            <input asp-for="@Model.products[i].Country" class="form-control" />
                        </td>
                        <td class="table-action">                            
                            <img src="~/icons/trash.svg" title="Delete" alt="Delete" height="18" width="18" onclick="DeleteRow(@i,'@Model.products[i].Name')">
                        </td>
                    </tr>
                }
            </tbody>
        </table>
        <button type="submit" class="btn btn-secondary btn-sm" asp-page-handler="Insert" value="Insert A">
            <i class="fas fa-save">Insert</i>
        </button>
        <button type="submit" class="btn btn-secondary btn-sm" asp-page-handler="Update" value="Update A">
            <i class="fas fa-save">Save</i>
        </button>
    </div>
    </form>

    <SCRIPT language="JavaScript" type="text/Javascript">
    <!--
    function DeleteRow(idno,desc) {
        if (confirm("Are you sure you wish to Delete Row " + desc)) {
            $('#multiform').attr('action', "multirowform?handler=Delete&id=" + idno);
             $("#multiform").submit();
          } else {            
          }

    }

    </SCRIPT>

标签: asp.net-corerazor-pages

解决方案


在删除行之前添加 modelstate.clear() 解决了我的问题。

        public IActionResult OnPostDelete(int? id)
        {
            if (ModelState.IsValid)
            {
                if (id == null)
                {
                    return NotFound();
                }
                int delid = id ?? 0;
                ModelState.Clear();
                products.RemoveAt(delid);
            }
            return Page();
       }

“如果您从表单中获取模型,并且想要操作来自客户端表单的数据并将其写回视图,则需要调用 ModelState.Clear() 来清除 ModelState 值。” https://patrickdesjardins.com/blog/modelstate-clear-is-required-to-display-back-your-model-object


推荐阅读