Good morning I'm trying to add Anti Forgery Token to my application made using Knockout.js This is my Model:
public partial class Course
{
[Key]
public int CourseID { get; set; }
public string CourseName { get; set; }
public string CourseDescription { get; set; }
}
This is my controller:
// POST: Home/Create
[HttpPost]
public string Create(Course course)
{
if (!ModelState.IsValid) return "Model is invalid";
_db.Courses.Add(course);
_db.SaveChanges();
return "Cource is created";
}
This is my View:
@model MVCCRUDKnockout.Models.Course
@{
ViewBag.Title = "Create";
}
<div class="form-horizontal">
<h4>Course</h4>
<hr>
<div class="form-group">
<label class="control-label col-md-2" for="CourseName">CourseName</label>
<div class="col-md-10">
<input class="form-control text-box single-line" id="CourseName" name="CourseName" type="text" value="" data-bind="value: CourseName">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="CourseDescription">CourseDescription</label>
<div class="col-md-10">
<input class="form-control text-box single-line" id="CourseDescription" name="CourseDescription" type="text" value="" data-bind="value: CourseDescription">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" data-bind="click: createCourse" value="Create" class="btn btn-default">
</div>
</div>
</div>
<div>
@Html.ActionLink("Back to List", "Read")
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/knockout-3.4.0.js"></script>
<script src="~/Scripts/KOScripts/KOCreate.js"></script>
This is my Script:
$(function () {
ko.applyBindings(modelCreate);
});
var modelCreate = {
CourseName: ko.observable(),
CourseDescription: ko.observable(),
createCourse: function () {
try {
$.ajax({
url: '/Home/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this), //Here the data wil be converted to JSON
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
};
function successCallback(data) {
window.location.href = '/Home/Read/';
}
function errorCallback(err) {
window.location.href = '/Home/Read/';
}
Now I try to change the code:
1) adding [ValidateAntiForgeryToken] to the controller;
2) adding @Html.AntiForgeryToken() to the View.
My problem is that I cannot edit the Script to make it work properly. How can I do this?