Jump to content

__RequestVerificationToken


wrb
 Share

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 comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...