Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

342
Views
Cómo pasar una List<T> de Ajax Post a .Net 5 Razor Pages Pagebehind

He visto algunas preguntas diferentes con respecto a los métodos de publicación de ajax, pero ninguna parece resolver mi problema.

Tengo una Vista parcial que está creando una matriz de objetos a través de javascript en el lado del cliente, y quiero tomar esta matriz y luego pasarla a mi página detrás de los archivos en mi aplicación Razor Pages como un tipo C# de Lista de T (T siendo mi objeto personalizado Nota).

Desafortunadamente, cuando los datos vuelven a mi método OnPostAddNotes, la lista siempre está vacía. Los datos pasan como se esperaba cuando solo se usa la clase Nota como modelo, pero por alguna razón no puedo hacer que pase la Lista de "Nota".

El "modelo de nivel superior" es un modelo de detalle de caracteres, que tiene una propiedad de CharacterNotes, que es una lista de tipo Nota.

Modelo/Personaje.cs

 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>(); } }

El tipo para CharacterNotes es una lista de notas que tiene estas propiedades.

Modelo/Nota de personaje.cs

 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; } } }

Esta es la Vista principal que tiene como Modelo el Modelo de Detalle de Personajes. Tiene un parcial de Notas de Personajes.

Vistas/CharacterDetail.cshtml

 @page "{id}" @model RPGInfo.Web.Pages.CharacterDetailModel @model { ViewData["Title"] = "Character Detail"; } <div> <partial name="_CharacterNotePartial" model="@Model.CharacterNotes" /> </div>

Vista parcial para crear las notas. Aquí es donde estoy tratando de enviar una lista de objetos de nota al método OnPostAddNote en el archivo Page Behind.

Compartido/_CharacterNotesPartial.cshtml

 @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>

Función y método Ajax para enviar datos en click=AddCurrentNotes(data). He intentado agregar y eliminar varias propiedades de Note para compilar el json, pero no se envía ninguna al parámetro en el método de publicación.

La página detrás del archivo tiene un método "OnPostAddNotes" que está conectado al botón Enviar y recibe un parámetro Lista de notas. El parámetro Lista de notas siempre regresa con Conteo de 0. Si cambio de Lista de notas a solo Nota como modelo, funciona como se esperaba, pero la Lista no.

Páginas/Personajes/CharacterDetail.cshtml.c s

 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(); } }

En el lado del cliente, las notas se crean a través de Javascript, y al mirar la carga útil, el objeto parece estar estructurado correctamente, sin embargo, la pestaña de red solo muestra los métodos ajax como pendientes. ¡Muchas gracias por su asistencia!

Código e imagen actualizados que muestran la nueva carga útil . Cambié la fecha en mi función ajax y eso se muestra en la carga útil, desafortunadamente, la Lista sigue volviendo como nula en mi archivo CharacterDetail.cshtml.cs.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

No estoy seguro de cuál es su data en su vista parcial, pero no es importante. Veo que su Payload contiene datos correctamente. Así que codifiqué la Carga útil para facilitar la prueba y le ofrecí una demostración funcional:

Puede ver que su Network contiene dos solicitudes para este controlador, esto se debe a que el tipo predeterminado del elemento <button> es enviar, por lo que primero enviará los datos del formulario al backend. Agregue type="button" como a continuación para evitar solicitudes múltiples:

 <button class="btn btn-primary" type="button" onclick="addCurrentNotes()">Submit Added Notes</button>

Cambie su js como a continuación:

Notas: Proporcione el valor predeterminado del formato de fecha y hora de noteDate en lugar de una cadena vacía.

 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()); } }) }

Agregue [FromBody] en su código de back-end:

 public ActionResult OnPostAddNotes([FromBody]List<Note> notes) { return RedirectToPage(); }

Notas:

Ajax no puede funcionar con RedirectToPage, si desea redirigir cuando ajax publique de nuevo, necesita agregar window.location.href="url" en la función de éxito.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!