Jump to content

__RequestVerificationToken


Recommended Posts

Would anyone guide something for the error below?

"The required anti-forgery form field "__RequestVerificationToken" is not present."

 

The error occurs when trying to delete a row in the table on the button below:

<button onclick="return false;">Excluir</button>
 $("#add").click(function () {        var token = $('[name=__RequestVerificationToken]').val();        $.ajax({            url: '@Url.Action("AddComponente", "Medicamento_formula")',            cache: false,            headers: { "__RequestVerificationToken": token },                       type: "POST",            data: $('#formcomp').serializeArray(),            success: function (data) {                if (data.success) {                    $('#tabelacomposicao > tbody:last').append('<tr>' + '<td hidden>' + data.id + '</td>' + '<td>' + data.descricao + '</td>' + '</td>' + '<td>' + data.excipiente + '</td>' + '<td>' + data.unidade_Medida + '</td>' + '<td>' + data.principio + '</td>' + '<td>' + data.quantidade + '</td>' + '<td>' + '<input type="image" src="/Images/excluir.png" onclick="clicado(this)">' + '</td>' + '</tr>');                    $('#formcomp')[0].reset();                    $("#validacaocomposicao").html("");                }                else {                    $("#validacaocomposicao").html(data.msg);                }            }        });        return false;    });    function clicado(a) {        var token = $('[name=__RequestVerificationToken]').val();        console.log($(a).closest('tr')[0].rowIndex);        var linhaIndex = $(a).closest('tr')[0].rowIndex;        var codigo = $(a).closest('tr').children('td')[0].innerText;                     $.ajax({            type: "POST",            url: '@Url.Action("DelComponente", "Medicamento_formula")',                       cache: false,            headers: { "__RequestVerificationToken": token },            contentType: 'application/json; charset=utf-8',            data: { codigo: codigo },            success: function (data) {                document.getElementById("tabelacomposicao").deleteRow(linhaIndex);                console.log("ok");            }        });    }

CONTROLLER:

 [AttributeUsage(AttributeTargets.Class)]        public class ValidateAntiForgeryTokenOnAllPosts : AuthorizeAttribute        {            public override void OnAuthorization(AuthorizationContext filterContext)            {                var request = filterContext.HttpContext.Request;                //  Only validate POSTs                if (request.HttpMethod == WebRequestMethods.Http.Post)                {                    //  Ajax POSTs and normal form posts have to be treated differently when it comes                    //  to validating the AntiForgeryToken                    if (request.IsAjaxRequest())                    {                        var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];                        var cookieValue = antiForgeryCookie != null                            ? antiForgeryCookie.Value                            : null;                        AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);                    }                    else                    {                        new ValidateAntiForgeryTokenAttribute()                            .OnAuthorization(filterContext);                    }                }            }        }[HttpPost]        [ValidateAntiForgeryToken]        public ActionResult DelComponente(string codigo)        {            var _Codigo = Convert.ToInt32(codigo);            Composicao.Remove(_Codigo);            return Json(new { success = true });        }

CREATE

@using (Html.BeginForm("Create", "Medicamento_formula", FormMethod.Post, new { id = "formularioprincipal" })){     @Html.AntiForgeryToken()    @Html.ValidationSummary(true)} <table class="table table-hover table-bordered" id="tabelacomposicao">                            <thead>                                <tr style="font-size:10px">                                    <th>                                        <i> NOME</i>                                    </th>                                    <th>                                        <i> EXCIPIENTE</i>                                    </th>                                    <th>                                        <i> UNIDADE DE MEDIDA</i>                                    </th>                                    <th>                                        <i> PRINCIPIO ATIVO</i>                                    </th>                                    <th>                                        <i> QUANTIDADE</i>                                    </th>                                    <th>                                        <i>EXCLUIR</i>                                    </th>                                </tr>                            </thead>                            <tbody id="linhascomp">                                @foreach (var item in @ViewBag.ComposicaoFormula)                                {                                    <tr style="font-size:10px">                                        <td>                                            @item.descricao                                        </td>                                        <td>                                            @item.excipiente                                        </td>                                        <td>                                            @item.unidade_Medida                                        </td>                                        <td>                                            @ViewBag.PrincipioAtivo.Find(item.cod_Principio_Ativo).descricao                                        </td>                                        <td>                                            @item.quantidade                                        </td>                                        <td>                                            <button onclick="return false;">Excluir</button>                                        </td>                                    </tr>                                }                            </tbody>                        </table>
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...