I have @Html.AntiForgeryToken() in view and [ValidateAntiForgeryToken] in controll, but still the error is there. Iam trying to access controller through Ajax. my current code as follows:
view:
@model learn.ViewModel.tblCategoryVM
@{
ViewBag.Title = "Ganacsi";
Layout = "~/Views/Shared/_sellerLayout.cshtml";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="main-wrapper">
<!-- navbar vertical -->
@{ Html.RenderAction("_navbarDashboard", "Home"); }
<!-- main -->
<main class="main-content-wrapper">
<!-- container -->
<div class="container">
<!-- row -->
<div class="row mb-8">
<div class="col-md-12">
<div class="d-md-flex justify-content-between align-items-center">
<!-- page header -->
<div>
<h2>Add New Category</h2>
<!-- breacrumb -->
<nav aria-label="breadcrumb">
<ol class="breadcrumb mb-0">
<li class="breadcrumb-item"><a href="#" class="text-inherit">Dashboard</a></li>
<li class="breadcrumb-item"><a href="#" class="text-inherit">Categories</a></li>
<li class="breadcrumb-item active" aria-current="page">Add New Category</li>
</ol>
</nav>
</div>
<div>
<a href="/dashboard/categories" class="btn btn-light">Back to Categories</a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12 col-12">
<!-- card -->
<div class="card mb-6 shadow border-0">
<!-- card body -->
<div class="card-body p-6 ">
@*<h4 class="mb-5 h5">Category Image</h4>*@
@*<div class="mb-4 d-flex">
<div class="position-relative">
<img class="image icon-shape icon-xxxl bg-light rounded-4" src="../assets/images/icons/bakery.svg" alt="Image">
<div class="file-upload position-absolute end-0 top-0 mt-n2 me-n1">
<input type="file" class="file-input ">
<span class="icon-shape icon-sm rounded-circle bg-white">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="currentColor" class="bi bi-pencil-fill text-muted" viewBox="0 0 16 16">
<path d="M12.854.146a.5.5 0 0 0-.707 0L10.5 1.793 14.207 5.5l1.647-1.646a.5.5 0 0 0 0-.708l-3-3zm.646 6.061L9.793 2.5 3.293 9H3.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.207l6.5-6.5zm-7.468 7.468A.5.5 0 0 1 6 13.5V13h-.5a.5.5 0 0 1-.5-.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.5-.5V10h-.5a.499.499 0 0 1-.175-.032l-.179.178a.5.5 0 0 0-.11.168l-2 5a.5.5 0 0 0 .65.65l5-2a.5.5 0 0 0 .168-.11l.178-.178z" />
</svg>
</span>
</div>
</div>
</div>*@
<h4 class="mb-4 h5 mt-5">Category Information</h4>
<div class="row">
<!-- input -->
<div class="mb-3 col-lg-6">
<label class="form-label">Category Name</label>
<input type="text" class="form-control" placeholder="Category Name" required id="categoryName">
</div>
<div class="mb-3 col-lg-6">
<label class="form-label">Publish</label>
<select class="form-select" id="publishDropdown">
@foreach (var status in Model.statusList)
{
<option value="@status">@status</option>
}
</select>
</div>
<!-- input -->
@*<div class="mb-3 col-lg-6">
<label class="form-label">Slug</label>
<input type="text" class="form-control" placeholder="Slug" required>
</div>*@
<!-- input -->
@*<div class="mb-3 col-lg-6">
<label class="form-label">Parent Category</label>
<select class="form-select">
<option selected>Category Name</option>
<option value="Dairy, Bread & Eggs">Dairy, Bread & Eggs</option>
<option value="Snacks & Munchies">Snacks & Munchies</option>
<option value="Fruits & Vegetables">Fruits & Vegetables</option>
</select>
</div>
<div class="mb-3 col-lg-6">
<label class="form-label">Date</label>
<input type="text" class="form-control flatpickr" placeholder="Select Date">
</div>*@
<div>
</div>
<!-- input -->
<div class="mb-3 col-lg-12 ">
<label class="form-label">Descriptions</label>
<div class="py-8" id="editor"></div>
</div>
<!-- input -->
<div class="mb-3 col-lg-12 ">
<label class="form-label" id="productSKU">Active/Disable</label><br>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="activeRadioOptions"
id="inlineRadio1" value="Y" checked>
<label class="form-check-label" for="inlineRadio1">Active</label>
</div>
<!-- input -->
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="activeRadioOptions"
id="inlineRadio2" value="N">
<label class="form-check-label" for="inlineRadio2">Disabled</label>
</div>
<!-- input -->
</div>
<div class="mb-3 col-lg-12 mt-5">
<h4 class="mb-4 h5">Meta Data</h4>
<!-- input -->
<div class="mb-3">
<label class="form-label">Meta Title</label>
<input type="text" class="form-control" placeholder="Title" id="metaTitle">
</div>
<!-- input with dynamic keyword display -->
<div class="mb-3">
<label class="form-label">Meta Description</label>
<textarea class="form-control" rows="3" id="metaKeyword" placeholder="Meta Description"></textarea>
</div>
<div id="keywordBox" class="keyword-box"></div>
</div>
<div class="col-lg-12">
<a href="#" class="btn btn-primary" id="saveCategoryBtn">
Create Product
</a>
<a href="#" class="btn btn-secondary ms-2">
Save
</a>
</div>
<div class="d-grid">
<small class="form-text clsErrorMsg" id="ErrMsg" style=" text-align: center; color:red;"></small>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
}
<script src="../assets/js/vendors/editor.js"></script>
<script>
const metaKeyword = document.getElementById('metaKeyword');
const keywordBox = document.getElementById('keywordBox');
metaKeyword.addEventListener('input', updateKeywordBox);
function updateKeywordBox() {
const keywordsArray = metaKeyword.value.split(/\s*,\s*/);
const keywordBoxContent = keywordsArray.map(keyword => `<span class="keyword-tag">${keyword.trim()} <span class="close-icon" onclick="removeKeyword(this)">×</span></span>`).join(' ');
keywordBox.innerHTML = keywordBoxContent;
}
function removeKeyword(element) {
const keyword = element.previousSibling.textContent.trim();
const keywordsArray = metaKeyword.value.split(/\s*,\s*/).filter(kw => kw !== keyword);
metaKeyword.value = keywordsArray.join(', ');
updateKeywordBox();
}
</script>
<script>
$(document).ready(function () {
$('#saveCategoryBtn').click(function () {
showLoader();
var csrfToken = $('input[name="__RequestVerificationToken"]').val();
console.log('CSRF Token:', csrfToken);
var categoryName = $('#categoryName').val();
var published = $('#publishDropdown').val();
var description = htmlEncode(document.getElementById('editor').innerHTML);
var status = $('input[name="activeRadioOptions"]:checked').val();
var metaTitle = $('#metaTitle').val();
var metaKeyword = $('#metaKeyword').val();
// var files = Array.from($('#uploadImage')[0].files);
if (!categoryName) {
displayError("Enter category Name ....");
return;
}
else if (!publishDropdown) {
displayError("Select Publish Type ....");
return;
} else if (!description) {
displayError("Enter Product description ....");
return;
} else if (!status) {
displayError("Select status ....");
return;
} else if (!metaTitle) {
displayError("Enter Meta Title ....");
return;
} else if (!metaKeyword) {
displayError("Enter Meta Keyword ....");
return;
}
else {
displayError("");
hideLoader();
}
var formData = new FormData();
formData.append('categoryName', categoryName);
formData.append('description', description);
formData.append('published', published);
formData.append('metaTitle', metaTitle);
formData.append('metaKeyword', metaKeyword);
formData.append('status', status);
//for (var i = 0; i < files.length; i++) {
// formData.append('files', files[i]);
// console.log(files[i]);
//}
//var imagePaths = files.map(file => '~/assets/images/products/' + file.name).join(',');
//formData.append('imagePaths', imagePaths);
$.ajax({
url: '/dashboard/AddSellerCategory',
type: 'POST',
headers: {
'RequestVerificationToken': csrfToken
},
data: formData,
contentType: false,
processData: false,
success: function (data) {
if (data === true) {
alert('Category saved successfully.');
location.href = 'dashboard/categories';
}
},
error: function (error) {
console.log(error);
alert('Error saving the Category.');
},
complete: function () {
hideLoader();
}
});
});
function displayError(errorMessage) {
$("#ErrMsg").css("display", "inline-block");
$("#ErrMsg").text(errorMessage);
hideLoader();
}
function htmlEncode(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
});
</script>
controller:
#region Add Category
public ActionResult add_category()
{
tblCategoryVM category = new tblCategoryVM();
category.statusList = BindCategoryType();
return View(category);
}
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public JsonResult AddSellerCategory(categoryVM category)
{
try
{
using (LearnDBEntities context = new LearnDBEntities())
{
SqlConnection con = new SqlConnection(context.Database.Connection.ConnectionString);
SqlDataReader sqlReader;
try
{
AntiForgery.Validate();
string strSQL = "Addtblcategory";
//List<string> imagePaths = new List<string>();
string ip = Request.UserHostAddress;
SqlCommand AccountCommand = new SqlCommand(strSQL, con);
if (con.State == ConnectionState.Closed)
con.Open();
AccountCommand.CommandType = CommandType.StoredProcedure;
AccountCommand.CommandText = strSQL;
AccountCommand.Parameters.Add(new SqlParameter("@Category", category.categoryName));
AccountCommand.Parameters.Add(new SqlParameter("@Published", category.published));
AccountCommand.Parameters.Add(new SqlParameter("@Description", category.description));
AccountCommand.Parameters.Add(new SqlParameter("@MetaTitle", category.metaTitle));
AccountCommand.Parameters.Add(new SqlParameter("@MetaKeyword", category.metaKeyword));
AccountCommand.Parameters.Add(new SqlParameter("@Show", category.status));
AccountCommand.Parameters.Add(new SqlParameter("@CreatedOn", DateTime.Now.ToString()));
AccountCommand.Parameters.Add(new SqlParameter("@createdBy", Session["CartUser"].ToString()));
sqlReader = AccountCommand.ExecuteReader(CommandBehavior.CloseConnection);
return Json(true, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
string message = ex.Message;
return Json(false, JsonRequestBehavior.AllowGet);
}
finally
{
con.Close();
}
}
}
catch (Exception ex)
{
ViewBag.ErrorMessage = "Error saving the product: " + ex.Message;
return Json(false, JsonRequestBehavior.AllowGet);
}
}
#endregion
ViewModel:
public class categoryVM
{
public string categoryName { get; set; }
public string description { get; set; }
public string published { get; set; }
public string metaTitle { get; set; }
public string metaKeyword { get; set; }
public string status { get; set; }
}
Iam getting token value in console.log.