Adding elements to a form using JQuery causes the “The anti-forgery token could not be decrypted” error on submit

157
December 30, 2019, at 07:10 AM

I have an MVC App, with a regular form that includes @Html.AntiForgeryToken(), however i have a javascript function, with JQuery .append() call that adds elements to the form, am using this function to include elements in which shall act as hiddenfor() elements within the form and values shall be serialized to the corresponding Post Controller method on submit,

as described below:

$('#DivHiddenAccountsSub').append("<input id=\"LstAccountsSubDisplay_" + objAccountSub.ID + "__ActId\" name=\"LstAccountsSubDisplay[" + objAccountSub.ID + "].ActId\" type=\"hidden\" value=\"" + objAccountSub.ActId + "\" />");

However, when i hit the submit button i get the following error: "The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster,

Note: The above listed code, after replacing the objAccountSub.ID, shall look something like: <input id="LstAccountsSubDisplay_0__ActId" name="LstAccountsSubDisplay[0].ActId" type="hidden" value="01001" />

How can i append elements to the form without breaking the AntiForgeryToken() value??

Answer 1

try to create the element first then append it as the following:

 $('#DivHiddenAccountsSub').append($("<input id=\"LstAccountsSubDisplay_" + objAccountSub.ID + "__ActId\" name=\"LstAccountsSubDisplay[" + objAccountSub.ID + "].ActId\" type=\"hidden\" value=\"" + objAccountSub.ActId + "\" />")); 
Rent Charter Buses Company
READ ALSO
how to access the html element using angularjs [duplicate]

how to access the html element using angularjs [duplicate]

For developers who used to the JQuery for many years, we used to get the html element alwaysI find it very tricky in angularjs, I'm looking for an equivalent of $(selector)

126
Navigate to new url with additional query when user clicks on a div

Navigate to new url with additional query when user clicks on a div

I'm trying to accomplish the following: when a div is clicked the user will go to a new url and it adds a query string to the url

91
jquery datatable Complex headers duplicate problem

jquery datatable Complex headers duplicate problem

I am working with jquery datatable

145
Why is my JSON response not recognized in another function?

Why is my JSON response not recognized in another function?

I'm building an app for an assignment for school that uses the Github APIYou search for a user, and it should return their Github repos in a list form, with links to their repos

106