I have a view that has an html form. This form posts data to two entities.The first entity is in a one-to-many relationship with the other.
This form has an html table where the user can add as many rows as needed. Then on submitting the form, data of form will be posted to entity1
and data inserted in the html table should be collected and added to entity2
, that has a many-to-one relationship with entity1
.
I collected data inserted by user in html table as a js array of objects and tried to send this as ajax to post action in the controller on form submission.
I had an error:
[The required anti-forgery form field "__RequestVerificationToken" is not present]
So I passed token in header and added authorization filter to post action data sent from ajax is not null, but it is received in controller as null.
How can I solve this?
cols.push("DIGITAL_FILE_TYPE_ID");
cols.push("DOCUMENT_LAPI_ID");
var digitalMapRows = [];
$("table#digital-map-table tbody tr").each(function () {
data = {};
var selectedDigitalMapVal =
$(this).data("selectedDigitalMapVal");
data[cols[0]] = selectedDigitalMapVal;
var documentId = $(this).data("documentID");
data[cols[1]] = documentId.toString();
digitalMapRows.push(data);
data = {};
});
var headers = { __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val() };
if (digitalMapRows != null) {
$.ajax({
headers: headers,
url: "@Url.Action("Initiate")",
type: "POST",
cache: false,
data: JSON.stringify(digitalMapRows),
dataType: "json",
success: function (succ) {
console.log(succ);
},
error: function (err) {
console.log(err.statusText);
}
});
}
And this is the post action I'm posting to from ajax. Should my data be included in viewmodel
rather than a separate argument? Hence data passed in this argument won't be filled in all cases.
[HttpPost]
//[ValidateAntiForgeryToken]
[ValidateHeaderAntiForgeryToken]
public ActionResult Initiate(SODViewModel vm,
IEnumerable<DIGITAL_MAPS> digitalMapRows)
{
//digitalMapRows returns as null