简体   繁体   English

Razor 页面 - 使用 AJAX 和 PartialView 更新 Model

[英]Razor Pages - Updating a Model with AJAX and PartialView

I'm starting to study Razor Pages, and using MongoDB as my database.我开始研究 Razor 页,并使用 MongoDB 作为我的数据库。

I finished my CRUD operations, and now I'm working on my main page.我完成了我的 CRUD 操作,现在我正在处理我的主页。

Main Page主页

But I can't understand how to update partially my page但我不明白如何部分更新我的页面

the first search (Default taking DateTime.Now) is already working as expected, but when I change the month selector, my page doesn't update with the current list I'm working with.第一次搜索(默认采用 DateTime.Now)已经按预期工作,但是当我更改月份选择器时,我的页面不会更新我正在使用的当前列表。

I'm using AJAX for this POST method on my View:我在我的视图上使用 AJAX 作为此 POST 方法:

(ContaView.cshtml) (ContaView.cshtml)

@page
@using System.Globalization
@model ControleContas.Pages.Contas.ContasViewModel
@{
}

<script>
    function changeDateSelector(date){
        var dataAtualizada = date.value;
        $.ajax({
            type: "POST",
            url: '/Contas/ContaView?handler=MonthSelector',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(dataAtualizada),
            headers:
            {
                "RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
            }
        });
    }
</script>

<div>
    <a class="nav-link text-dark" asp-area="" asp-page="/Contas/ContaCadastro"><button type="button" class="btn btn-primary">Cadastrar Cartão</button></a>
</div>

<th scope="row"><button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#CreateModal">Criar</button></th>
<br />
<div id="titleMonth">@Model.dataCorrente.ToString("MMMM", CultureInfo.CreateSpecificCulture("pt-br"))</div>
<br />
<button type="button" class="btn btn-light">&larr;</button>
<input min="@(DateTime.Now.AddYears(-10).ToString("yyyy-MM"))" max="@(DateTime.Now.AddYears(10).ToString("yyyy-MM"))" onchange="changeDateSelector(this)" asp-for="dataCorrente" type="month">
<button type="button" class="btn btn-light">&rarr;</button>

<!-- Modal -->
<div class="modal fade" id="CreateModal" tabindex="-1" role="dialog" aria-labelledby="CreateTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="CreateTitle">Criar Conta</h5>
                <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <input id="UserModal" hidden="hidden"></input>
                    <div class="form-group">
                        <label>Nome da Conta</label>
                        <input id="ValorCreateModal" asp-for="conta.Nome" type="text" class="form-control" placeholder="Nome" />
                    </div>
                    <div class="form-group">
                        <label>Valor</label>
                        <input id="ValorCreateModal" asp-for="conta.Valor" type="text" class="form-control" placeholder="Valor" />
                    </div>
                    <div class="form-group">
                        <label>Data</label>
                        <input id="DataCreateModal" asp-for="conta.Data" type="date" class="form-control" placeholder="Data da Conta" />
                    </div>
                    <div class="form-group">
                        <label>Prestações</label>
                        <input id="PrestacoesCreateModal" asp-for="conta.TotalPrestacoes" type="number" class="form-control" placeholder="Insira aqui a Quantidade de Prestações (1 - à Vista)" />
                    </div>
                    <div class="form-group">
                        <label>Pago?</label>
                        <input id="DespesaCreateModal" asp-for="conta.Pago" type="checkbox" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Despesa?</label>
                        <input id="DespesaCreateModal" asp-for="conta.Despesa" type="checkbox" class="form-control" />
                    </div>
                    <!--
                        TODO: Criar um CheckBox para identificar se é uma conta para cartão, se for habilitar Selection para apresentar os cartões e assim vincular ele se não, vincular ao identity Logado.
                     <div class="form-group">
                        <label>Cartão?</label>
                        <input id="FimCartaoModal" type="text" class="form-control" placeholder="Fim Cartão" />
                    </div>-->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" asp-page-handler="create" class="btn btn-primary">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<table class="table">
    <tr>
        <th>Id</th>
        <th>Nome</th>
        <th>Valor</th>
        <th>Data</th>
        <th>Prestação</th>
        <th>Cartão</th>
        <th>Pago?</th>
        <th>Despesa?</th>
        <th></th>
        <th></th>
    </tr>
    @foreach (var conta in Model.contas)
    {
        <tr>
            <th>@conta._id</th>
            <th>@conta.Nome</th>
            <th>@conta.Valor</th>
            <th>@conta.Data.ToShortDateString()</th>
            <th>@(conta.TotalPrestacoes == 1 ? "" : $"{conta.PrestacaoAtual}/{conta.TotalPrestacoes}")</th>
            <th>@conta.CartaoId</th>
            <th>@(conta.Pago ? "Sim" : "Não")</th>
            <th>@(conta.Despesa ? "Sim" : "Não")</th>
            <th><button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#CreateModal">Editar</button></th>
            <th><button type="button" class="btn btn-danger">Deletar</button></th>
        </tr>
    }
</table>

ContaView.cshtml.cs ContaView.cshtml.cs

using ControleContas.DTO.Contas;
using ControleContas.Models.Contas;
using ControleContas.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel.DataAnnotations;

namespace ControleContas.Pages.Contas
{
    public class ContasViewModel : PageModel
    {
        private readonly ContaDTO contaDTO;

        [BindProperty]
        public List<Conta> contas { get; set; }

        [BindProperty]
        public Conta conta { get; set; }

        [BindProperty]
        [DataType(DataType.Date)]
        public DateTime dataCorrente { get; set; } = DateTime.Now;

        public ContasViewModel(IConfiguration config)
        {
            this.contaDTO = new ContaDTO(config);
        }

        public void OnGet()
        {
            contas = BuscarContasUsuarioMes(User.Identity.Name, dataCorrente);
        }

        public IActionResult OnPostCreate()
        {
            conta.NomeUsuario = User.Identity.Name;
            if(conta.TotalPrestacoes > 1)
            {
                var dataBase = conta.Data;
                List<Conta> prestacoesContas = new List<Conta>();
                for (int i = 0; i < conta.TotalPrestacoes; i++)
                {
                    var contaPrestacao = new Conta
                    {
                        CartaoId = conta.CartaoId,
                        Despesa = conta.Despesa,
                        NomeUsuario = conta.NomeUsuario,
                        Nome = conta.Nome,
                        Pago = false,
                        PrestacaoAtual = i + 1,
                        Valor = conta.Valor,
                        TotalPrestacoes = conta.TotalPrestacoes,
                        Data = dataBase
                    };
                    dataBase = dataBase.AddMonths(1);
                    prestacoesContas.Add(contaPrestacao);
                }
                contaDTO.CreateMany(prestacoesContas, contaDTO.Database, contaDTO.ContaCollection);
            }
            else
            {
                conta.PrestacaoAtual = 1;
                conta.Pago = false;
                contaDTO.Create(conta, contaDTO.Database, contaDTO.ContaCollection);
            }
            return Redirect("ContaView?data=" + dataCorrente.Year + dataCorrente.Month);
        }

        public PartialViewResult OnPostMonthSelector([FromBody] string dataAtualizada)
        {
            dataCorrente = DateTime.ParseExact(dataAtualizada, "yyyy-MM", null);
            contas = BuscarContasUsuarioMes(User.Identity.Name, dataCorrente);
            return Partial("ContaView", contas);
        }

        private List<Conta> BuscarContasUsuarioMes(string user, DateTime data)
        {
            return contaDTO.buscaContasUsuario(user).Where(c => c.Data.Month == dataCorrente.Month && c.Data.Year == dataCorrente.Year).ToList();
        }
    }
}

I'm trying with the Partial() found around some sites, but Im not figuring out how to update my List of object <Conta> on my page.我正在尝试使用在某些网站周围找到的 Partial(),但我不知道如何更新我页面上的 object <Conta> 列表。

Would like some help to understand this process想要一些帮助来理解这个过程

I know how to do this with the normal <form> processo on my month selector, but I'd like to learn how to do properly this ajax call (starter in front end, worked as only Back-end dev 3 years)我知道如何使用我的月份选择器上的普通 <form> processo 来执行此操作,但我想学习如何正确执行此 ajax 调用(前端启动器,仅作为后端开发人员工作 3 年)

Using .NET Core 6.0使用 .NET 核心 6.0

Make the page update the list with the date passed through ajax使用通过 ajax 的日期使页面更新列表

You can try to use a partial view in Pages/Shared ,replace the html in ajax success:你可以尝试在Pages/Shared中使用局部视图,将 ajax 中的 html 替换成功:

Pages/Shared/Partial:页面/共享/部分:

@model List<Conta>
<table class="table">
    <tr>
        <th>Id</th>
        <th>Nome</th>
        <th>Valor</th>
        <th>Data</th>
        <th>Prestação</th>
        <th>Cartão</th>
        <th>Pago?</th>
        <th>Despesa?</th>
        <th></th>
        <th></th>
    </tr>
    @foreach (var conta in Model)
    {
        <tr>
            <th>@conta._id</th>
            <th>@conta.Nome</th>
            <th>@conta.Valor</th>
            <th>@conta.Data.ToShortDateString()</th>
            <th>@(conta.TotalPrestacoes == 1 ? "" : $"{conta.PrestacaoAtual}/{conta.TotalPrestacoes}")</th>
            <th>@conta.CartaoId</th>
            <th>@(conta.Pago ? "Sim" : "Não")</th>
            <th>@(conta.Despesa ? "Sim" : "Não")</th>
            <th><button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#CreateModal">Editar</button></th>
            <th><button type="button" class="btn btn-danger">Deletar</button></th>
        </tr>
    }
</table>

ajax: ajax:

 function changeDateSelector(date){
        var dataAtualizada = date.value;
        $.ajax({
            type: "POST",
            url: '/Contas/ContaView?handler=MonthSelector',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(dataAtualizada),
            headers:
            {
                "RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
            },
            success:function(data){
                $("#test").html(data);
            }
        });
    }

ContaView.cshtml: ContaView.cshtml:

<div id="test">
    <partial name="Partial" model=@Model.contas />
</div>

ContaView.cshtml.cs: ContaView.cshtml.cs:

public PartialViewResult OnPostMonthSelector([FromBody] string dataAtualizada)
        {
            dataCorrente = DateTime.ParseExact(dataAtualizada, "yyyy-MM", null);
            contas = BuscarContasUsuarioMes(User.Identity.Name, dataCorrente);
            return Partial("Partial", contas);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM