首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将List<T>从Ajax Post传递到.Net 5 Razor Pages Pages

如何将List<T>从Ajax Post传递到.Net 5 Razor Pages Pages
EN

Stack Overflow用户
提问于 2022-01-17 14:09:00
回答 2查看 557关注 0票数 2

我见过一些关于ajax方法的不同问题,但似乎没有一个能解决我的问题。

我有一个部分视图,它通过客户端的javascript创建一个对象数组,我想将这个数组作为T的C#类型列表(T是我的自定义对象注释)传递到Razor Pages应用程序中的文件后面的页面。

不幸的是,当数据返回到我的OnPostAddNotes方法时,列表总是空的。当只使用Note类作为模型时,数据会像预期的那样传递,但由于某种原因,我无法让它传递"Note“列表。

“顶层模型”是一个字符细节模型,它的属性为CharacterNotes,它是一个类型为Note的列表。

Model/Character.cs

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace RPGInfo.Web.Models
{
    public class Character : BaseEntity
    {
        public List<Note> CharacterNotes { get; set; } = new List<Note>();
    }
}

CharacterNotes类型是一个具有以下属性的备注列表。

Model/CharacterNote.cs

代码语言:javascript
复制
 using System;
    using System.ComponentModel.DataAnnotations;
    
    namespace RPGInfo.Web.Models
    {
        public class Note : BaseEntity
        {
            [Required]
            [MaxLength(40)]
            public string NoteTitle { get; set; }
    
            public DateTime NoteDate { get; set; }
    
            [Required]
            [MaxLength(500)]
            public string NoteContent { get; set; }
        }
    }

这是一个主视图,它的模型是字符细节模型。它有部分字符注释。

Views/CharacterDetail.cshtml

代码语言:javascript
复制
@page "{id}"
@model RPGInfo.Web.Pages.CharacterDetailModel
@model {
   ViewData["Title"] = "Character Detail";
      }
 <div>
   <partial name="_CharacterNotePartial" model="@Model.CharacterNotes" />
 </div>

创建注释的部分视图。下面是我试图向Page中的OnPostAddNote方法发送Note列表的地方。

Shared/_CharacterNotesPartial.cshtml

代码语言:javascript
复制
  @using RPGInfo.Web.Models
    @model List<Note>
    <h4>Character Notes</h4>
    
    <div class="row">
        <ul class="list-group col-12" id="newNote">
        </ul>
    </div>
    
    <form asp-page-handler="AddNotes" class="mt-4 mb-4">
    
        <div class="row">
            <div class="form-group col-6">
                <label for="NoteTitle">Title</label>
                <input type="text" id="noteTitle" name="NoteTitle" class="form-control">
            </div>
    
            <div class="form-group  col-6">
                <label for="NoteDate">Date</label>
                <input type="datetime" id="noteDate" name="NoteDate" class="form-control">
            </div>
        </div>
    
        <div class="form-group">
            <label for="NoteContent">Content</label>
            <input type="text" id="noteContent" name="NoteContent" class="form-control">
        </div>
    
        <button type="button" id="addNoteForm" class="btn btn-primary">Note Add</button>
    
        @Html.AntiForgeryToken()
        <button class="btn btn-primary" type="button" onclick="addCurrentNotes(data)"> Submit Added Notes</button>
    
    </form>
    
    <style>
        .note-style {
            word-wrap: break-word;
        }
    
    </style>
    
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript">
    
        data = [];
    
        $("#addNoteForm").click(function() {
           addNote();
        });
    
        $("#removeNote").click(function() {
            removeNote();
        });
    
         function addData(item) {
          data.push(item);
          console.log(data);
         }
    
         function removeData(itemToRemove) {
           $(itemToRemove).on("click", itemToRemove, function() {
           $(this).remove();
    
            var index = data.indexOf(itemToRemove.text());
            console.log(index);
            data.splice(index, 1);
            console.log(data);
             });
           }
    
          function addNote() {
           var noteTitle = $('input[id="noteTitle"]').val();
           var noteDate = $('input[id="noteDate"]').val();
           var noteContent = $('input[id="noteContent"]').val();
    
           var listItemId = getListItemId(4).toLowerCase();
    
           console.log(listItemId + ' ' + noteDate + ' ' + noteTitle + ' ' + noteContent);
    
           var listItemToAppend =  '<li id="li-'+ listItemId + '" class="list-group-item rmv_btn'+ listItemId + '">'
                     + '<div class="row">'
                       + '<div class="col-10 note-style">'
                           + noteTitle + ' ' + noteDate + ' ' + noteContent
                       + '</div>'
                       + '<div class="col-2">'
                           + '<button type="button" id="btn-'+ listItemId +'" class="rmv_btn'+ listItemId + ' btn btn-danger btn-sm">' + "Remove" + '</button>'
                       + '</div>'
                     + '</div>'
                  + '</li>'
    
            $("#newNote").append(listItemToAppend);
    
            var newItem = $('#newNote').find('#li-'+ listItemId).text();
            addData(newItem);
    
            var itemToRemove = $('#newNote').find('#li-'+ listItemId);
            removeData(itemToRemove);
    
           }
    
           function getListItemId(length) {
               var result = '';
               var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
               var charactersLength = 4;
               for ( var i = 0; i < length; i++ ) {
                 result += characters.charAt(Math.floor(Math.random() *
                 charactersLength));
                 }
    
               return result;
            }
    
           function addCurrentNotes() {
              var notes = [];
    
              for(let i = 0; i < 2; i++) {
                 var note = {};
                 note.noteTitle = "";
                 note.noteDate = "";
                 note.noteContent = "Content" + i;
                 notes.push(note);
              }
    
              notes = JSON.stringify(notes);
    
              $.ajax({
                  contentType: 'application/json; charset=utf-8',
                  dataType: 'json',
                  type: 'post',
                  url: window.location.href + "?handler=AddNotes",
                  data: notes,
                  success: function() {
                     window.location.href="url";
                  },
                  beforeSend: function (xhr) {
                                xhr.setRequestHeader("XSRF-TOKEN",
                                $('input:hidden[name="__RequestVerificationToken"]').val());
                               }
              });
    
            };
    
    </script>

在click=AddCurrentNotes( data )上发送数据的函数和Ajax方法。我尝试从Note中添加和删除各种属性来构建json,但是没有任何属性被发送到post方法的参数中。

文件后面的页面有一个"OnPostAddNotes“方法,该方法连接到submit按钮,并接收一个Note参数列表。Note参数的列表总是以0的计数返回。如果我从备注列表切换到仅作为模型的Note,它可以像预期的那样工作,但是列表不工作。

Pages/Characters/CharacterDetail.cshtml.cs

代码语言:javascript
复制
namespace RPGInfo.Web.Pages
{
    public class CharacterDetailModel : PageModel
    {
       
        [BindProperty]
        public Character Character { get; set; }

        public void OnGet(int id)
        {
            Character = _context.Characters.Where(x => x.Id == id).FirstOrDefault();

            Character.CharacterNotes = _context.Notes.Where(note => note.CharacterId == id).ToList();   
        }

        [BindProperty]
        public Note CharacterNote { get; set; }

        [BindProperty]
        public List<Note> CharacterNotes { get; set; }

        public ActionResult OnPostAddNotes([FromBody]List<Note> notes)
        {
            // **List<Note> is null here**
            return RedirectToPage();
        }

    }

在客户端,注释是通过Javascript创建的,当查看有效负载时,对象的结构看起来是正确的,然而,网络选项卡只是将ajax方法显示为挂起。非常感谢您的帮助!

更新的代码和图像显示新的有效载荷。更改了ajax函数中的日期并显示在有效负载中,不幸的是,列表在我的CharacterDetail.cshtml.cs文件中仍然返回为null。

EN

回答 2

Stack Overflow用户

发布于 2022-01-18 02:41:25

不确定部分视图中的data是什么,但这并不重要。我看到你的有效载荷包含数据成功。因此,我只是硬编码的有效载荷,以便于测试,并给你一个工作的演示:

您可以看到您的Network包含对此处理程序的两个请求,即<button>元素默认类型为submit,因此它将首先将表单数据提交给后端。添加如下所示的type="button"以避免多次请求:

代码语言:javascript
复制
<button class="btn btn-primary" type="button" onclick="addCurrentNotes()">Submit Added Notes</button>

将您的js更改如下:

注释:请提供noteDate日期时间格式默认值,而不是空字符串.

代码语言:javascript
复制
function addCurrentNotes(){
    var notes=[];
    for(let i =0; i < 2;i++)
    {
        var note = {};
        note.noteTitle="";
        note.noteDate=new Date('0001-01-01');   //change here....
        note.noteContent="Content"+i;
        notes.push(note);
    }
    
    notes=JSON.stringify(notes);       //change here.....
    $.ajax({
        contentType:"application/json; charset=utf-8",
        dataType:'json',
        type:'post',
        url:window.location.href+"?handler=AddNotes",
        data:notes,
        success:function()
        {
            console.log("suceess");
        },
        beforeSend:function(xhr){
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        }
    })
}

在后端代码中添加[FromBody]

代码语言:javascript
复制
public ActionResult OnPostAddNotes([FromBody]List<Note> notes)
{
    return RedirectToPage();
}

备注:

Ajax无法使用RedirectToPage,如果您想在ajax回发时重定向,则需要在success函数中添加window.location.href="url"

票数 1
EN

Stack Overflow用户

发布于 2022-09-09 10:06:08

样本模型

代码语言:javascript
复制
 public class Test
 {
      public int Id { get; set; }
      public string Name { get; set; }
 }

后端码

代码语言:javascript
复制
public IActionResult OnPostSaveData(List<Test> objTest)
{
    //do whatever you want
}

在前端文件中添加ajax调用,如下所示

代码语言:javascript
复制
var urlVal = "@Url.Page("/index/")?handler=SaveData";

        $.ajax({
            type: "POST",
            url: urlVal,
            headers:
            {
                "RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            data: {
                "objTest": [{ "ID": 1, "Name": "buddhika" }, { "ID": 2, "Name": "buddhika123" }]
                },
            success: function (response) {
            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                 alert(response.responseText);
            }
        });
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70742700

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档