Two Viewmodels in one View

Asked

Viewed 108 times

0

I have a problem, let’s explain:

I have a page called Index where I re-address all the clientes from my database in a table, in this table there is a delete button that opens a Modal de Confirmação which creates a Form with a field Hidden, my question is, how can I use ViewModels of IndexClientViewModel and DeleteClientViewModel, and are on the same page, because today when I try to delete, I get the following error:

FormatException: TODO: Malformed input.

InvalidOperationException: The antiforgery token could not be decrypted.

I believe that the 1º Erro, is because of Viewmodel, and the second is a problem generated by 1º Erro,

Index.cshtml:

@using X.PagedList.Mvc.Core
@model X.PagedList.StaticPagedList<ApplicationClient>
@{
    ViewBag.Title = "Clientes";
}

<table class="table table-hover">
    <tbody>
        @foreach (var cliente in Model)
        {
            <tr>
                <td>
                     <h6>
                         <small class="text-muted">
                             <i class="fa fa-user"></i>
                         </small>
                         <a href="#"> @cliente.Nome</a>
                     </h6>
                     <small class="text-muted">
                         <i class="fa fa-phone"></i>
                          @foreach (var telefones in cliente.ClientesTelefone)
                          {
                          <span>-</span> @Html.DisplayFor(model => telefones.Telefone)
                          }
                     </small>
                     <br />
                     <small class="text-muted">
                         <i class="fa fa-envelope"></i>
                         @foreach (var emails in cliente.ClientesEmail)
                         {
                             <span>-</span> @Html.DisplayFor(model => emails.Email)
                         }
                     </small>
                </td>
                <td><span class="label label-success">Ativo</span></td>
                <td class="text-nowrap">
                    <span data-toggle="modal" data-target=".editClient" data-id="@cliente.Id">
                        <button class="btn btn-transparent" data-toggle="tooltip" data-original-title="Editar"> 
                             <i class="fa fa-pencil text-inverse m-r-10"></i>
                        </button>
                    </span>
                    <span data-toggle="modal" data-target=".deleteClient" data-client="@cliente.Id" data-name="@cliente.Nome">
                         <button class="btn btn-transparent" data-toggle="tooltip" data-original-title="Excluir"> 
                             <i class="fa fa-close text-danger"></i> 
                         </button>
                   </span>
               </td>
          </tr>
   }
   </tbody>

Modal Confirmação que está na pagina Index:

<div class="modal fade deleteClient" tabindex="-1" role="dialog" aria-labelledby="deleteClientLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h4 class="modal-title" id="deleteClientLabel"></h4>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            <ul>
                <li>* Não será possível desfazer esta exclusão;</li>
                <li>* Não será possível acessar aos dados deste cliente;</li>
                <li>* Os agendamentos para este cliente serão excluidos do sistema;</li>
            </ul>
            <form asp-route-returnurl="@ViewData["ReturnUrl"]" asp-action="Delete" asp-controller="Client" id="deleteClientForm">
                <input name="Id" type="hidden" class="form-control" id="clientDelete">
            </form>
            <br />
            <span class="text-error"><b>Tem certeza que deseja excluir esse cliente ?</b></span>
        </div>
        <div class="modal-footer">
            <button type="submit" class="btn btn-default" data-dismiss="modal">Cancelar</button>
            <button type="submit" class="btn btn-danger" onclick="$('#deleteClientForm').submit();">Excluir</button>
        </div>
    </div>
</div>

Controller:

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Delete(DeleteClientViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;

        var client = await _clientManager.GetClientId(model.Id);

        if (client == null)
        {
            throw new ApplicationException($"Não é possível carregar o cliente com o ID '{client.Id}'.");
        }

        var result = await _clientManager.DeleteClientAsync(client);

        TempData["MensagemSucesso"] = "Cliente deletado com sucesso";

        return RedirectToAction("Index");
    }

DeleteClientViewModel:

public class DeleteClientViewModel
{
    [Required]
    public long Id { get; set; }
}

Javascript:

$('.deleteClient').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var id = button.data('client');
var name = button.data('name'); // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('Excluir Cliente: '  + name)
modal.find('.modal-body input').val(id)

});

  • Create a new one that declares them both and work with her... But the mistake has nothing to do with it... Include the controller in the question and if you are not implementing, do not use the Antiforgerytokenvalidation annotation

  • Where is the post code?

  • I added more data to the question @Leandro Angelo

  • 1

    Remove the [ValidateAntiForgeryToken], the post is only the Submit? how many ids deleteClientForm you have on screen?

  • I do the Post, by Model I put in the question

  • Just an ID, put through a Javascript, I also put in question

  • 1

    Removed the [ValidateAntiForgeryToken]?

  • I removed yes, now I am able to send perfectly, only this happening some other mistakes, but it would have some way to maintain the [ValidateAntiForgeryToken] ?

  • Inspecting the form, you saw if Razor created a Hidden __RequestVerificationToken ?

  • You created the Hidden field yes

  • So unfortunately I can’t reproduce your problem

  • solved that problem?

Show 7 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.