This is my server-side code that adds data to db:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,UsersLanguage,OtherLanguage,Notes,Difficulty")] Word word)
{
if (ModelState.IsValid)
{
word.LastReviewed = DateTime.Now;
word.NextReview = DateTime.Now;
word.OwnerName = User.Identity.Name;
word.ReviewInterval = 0;
if (String.IsNullOrEmpty(word.OwnerName))
return View(word);
db.Words.Add(word);
db.SaveChanges();
return RedirectToAction("Create", new { addingSuccess = true });
}
return View(word);
}
I want to add some data to database using javascript. So I wrote this:
$.ajax({
type: "POST",
url: "/Words/Create",
data: { "UsersLanguage": questionToAdd, "OtherLanguage": answerToAdd }
}).success(function (data) {
console.log("Added");
$(this).parent().fadeOut(1000);
}).fail(function (data) {
console.error("cannot add word");
});
The problem is: this javascript code actually doesn't work. I'm getting error: "The required anti-forgery form field [...] is not present".
I think the reason is I have to send to server exactly the same object as server's "Word". OK, I could make variable in javascript that will look like "Word" class, but what if I once wanted to change "Word" class on my server? I would have to jump through all my scripts that send "Word" to server and change these js objects.
How to avoid that? How could I send some data without knowledge about how Word class is built? How can I send this "Word" to server without all data and make server to create missing variables?