【问题标题】:Manipulating data in database by passing IDs of check-boxes checked通过传递选中的复选框的 ID 来操作数据库中的数据
【发布时间】:2019-07-11 15:53:42
【问题描述】:

我正在设置一个 asp.net 网络应用项目。现在解决问题: (我是 Ajax、JQuery 和 Asp.net 的新手)

1) 我找到了一种将复选框的 ID 存储在字符串“CommaSeparatedIDs”中的方法 - 在 Index.cshtml 文件中(SaveFinished() 函数)

2) 在“Index.cshtml.cs”中定义“SaveFinished()”函数。我不知道如何定义函数/在文件中定义它的位置。函数的用途:具有在 1) 中定义的字符串参数,它使用 ID 操作数据库。

3) 最后,“SaveFinished()”的实现可能有我无法指出的错误。

我尝试在“Index.cshtml.cs”的不同区域定义函数“SaveFinished()”,但该函数从未被识别或引用,我也不知道该函数的类型应该是什么。

Index.cshtml:

<table class="table" id="MainTable">  // (Table used to define the various entries)
...
...
   <th>
      <a class="btn btn-success" onclick=SaveFinished()>Done</a> // JS function SaveFinished()
   </th>
...
...
    @foreach (var item in Model.ExcelData) // ExcelData is the object defined in Index.cshtml.cs (given below)

        <tr>
           <td>
               <input id="@item.ID" type="checkbox" />
           </td>
        ...
        ...
       </tr>
// I think I have errors below which I can't figure out.
<script>

    var SaveFinished = function () {
        var ArrItem = [];
        var CommaSeparatedIDs = "";

        $("MainTable tbody tr input[type=checkbox] ").each(function () {
            debugger
            var checkId = $(val).attr("id");
            var IsChecked = $("#" + checkId).is(":checked", true);
            if (IsChecked) {
                ArrItem.push(checkId);
            }
        })
        if (ArrItem.length != 0) {
            CommaSeparatedIDs = ArrItem.toString();
            $.ajax({
                url: "/Excel_Data/Index", <!--This should be the URL of the page?-->
                type: "POST",
                data: { MainTable: CommaSeparatedIDs },
                success: function (response) {
                     <!-- What should I do here? I'm new to Ajax and JQuery -->
                }
            })
        }
    }
</script>

索引.cshtml.cs:

namespace Customer.Pages.Excel_Data
{
    public class IndexModel : PageModel
    {
        private readonly Customer.Models.CustomerContext _context;
        public IndexModel(Customer.Models.CustomerContext context)
        {
            _context = context;
        }
        #region Variables

        public async Task OnGetAsync()
        {
         #region Data manipulation and setting variables      
        } 
    }
}

我的预期结果是将“SaveFinished()”函数中的字符串“CommaSeparatedIDs”传递给页面的逻辑部分——“Index.cshtml.cs”并操作数据库。

【问题讨论】:

  • 你的模型和 Index.cshtml.cs 中的 post 处理程序的定义是什么?

标签: c# asp.net ajax asp.net-mvc asp.net-core


【解决方案1】:

不清楚你的模型和后处理程序的定义,下面是工作示例,你可以参考

型号

public class ExcelData
{
    public int ID { get; set; }
    public string Name { get; set; }
}

Index.cshtml.cs

public class IndexModel : PageModel
{
    private readonly RazorPages2_1Project.Data.RazorPagesDbContext _context;

    public IndexModel(RazorPages2_1Project.Data.RazorPagesDbContext context)
    {
        _context = context;
    }

    public IList<ExcelData> ExcelData { get;set; }

    public async Task OnGetAsync()
    {
        ExcelData = await _context.ExcelData.ToListAsync();
    }

    public async Task<IActionResult> OnPostAsync([FromBody]string CommaSeparatedIDs)
    {
       //stuff you want
    }
}

您的项目是 Razor Pages 。 Razor Pages 旨在自动保护免受 跨站点请求伪造 (CSRF/XSRF) 攻击。您不必编写任何额外的代码。防伪令牌生成和验证自动包含在 Razor 页面中。如果发生 400 bad request 错误,则页面上不存在 AntiForgeryToken。使用 @Html.AntiForgeryToken() 显式添加如下:

@Html.AntiForgeryToken()

<table class="table" id="MainTable">
<thead>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.ExcelData[0].Name)
        </th>
        <th>
            <a class="btn btn-success" onclick="SaveFinished()">Done</a>
        </th>
        <th></th>
    </tr>
</thead>
<tbody>
    @foreach (var item in Model.ExcelData)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                <input id="@item.ID" type="checkbox" />
            </td>
            <td>
                <a asp-page="./Edit" asp-route-id="@item.ID">Edit</a> |
                <a asp-page="./Details" asp-route-id="@item.ID">Details</a> |
                <a asp-page="./Delete" asp-route-id="@item.ID">Delete</a>
            </td>
        </tr>
    }
</tbody>
</table>
@section Scripts
{
<script type="text/javascript">

    function SaveFinished() {
        var ArrItem = [];
        var CommaSeparatedIDs = "";

        $("#MainTable tbody tr input[type=checkbox]").each(function () {
           // debugger;
            var checkId = $(this).attr("id");
            var IsChecked = $(this).is(":checked");
            if (IsChecked) {
                ArrItem.push(checkId);
            }
        });
        if (ArrItem.length != 0) {
            CommaSeparatedIDs = ArrItem.toString();
            $.ajax({
                url: "/Excel_Data/Index",
                type: "POST",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                contentType: "application/json",
                data: JSON.stringify(CommaSeparatedIDs),
                success: function (response) {
                    alert(response);
                }
            });
        }
    }
</script>
}

由于脚本在名为 XSRF-TOKEN 的标头中发送令牌,因此配置防伪服务以查找 XSRF-TOKEN 标头:

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc();
  services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
}

参考:

Handle Ajax Requests in ASP.NET Core Razor Pages

https://www.tutorialsteacher.com/jquery/jquery-ajax-method

https://www.w3schools.com/jquery/jquery_syntax.asp

【讨论】:

  • 嘿!这么晚才回复很抱歉!您对模型和后处理程序的定义足够接近并且可以达到目的。但是,OnPostAsync 引发了错误,不得不将其更改为 public void OnPostAsync()。我还没有朝这个方向前进,因为必须在项目的其他部分工作!感谢您的帮助,不胜感激:)
猜你喜欢
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
  • 2015-10-13
  • 2018-03-16
  • 1970-01-01
  • 2021-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多