通过传递已选中复选框的ID来处理数据库中的数据

时间:2019-07-11 15:53:42

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

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

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

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

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

我尝试在“ Index.cshtml.cs”的不同区域中定义函数“ SaveFinished()”,但该函数从未得到识别或引用,我也不知道该函数的类型。 / p>

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>

Index.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”并操纵数据库。

1 个答案:

答案 0 :(得分:0)

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

型号

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。 剃刀纸页旨在自动防御跨站点请求伪造(CSRF / XSRF)攻击。您无需编写任何其他代码。 Razor Pages中会自动包含防伪令牌的生成和验证。如果发生400错误的请求错误,则该页面上没有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