Not sure what's wrong with my request but apparently the controller action doesn't receive my post. I want to post this form using antiforgery token and i also want to use ajax request. For this reason, I didn't use the default aspnet core form which include antiforgery token but instead i used the html helper @Html.AntiforgeryToken()
. Any idea where the problem come from?
@model RunViewModel
@{
ViewData["Title"] = "Run";
}
<h1 class="text-info">@ViewData["Title"]</h1>
<form id="run-form">
@Html.AntiForgeryToken()
<div class="form-group">
<label asp-for="InstanceName"></label>
<input asp-for="InstanceName" class="form-control" placeholder="Enter an instance name here..." />
</div>
<div class="form-group">
<label asp-for="DatabaseName"></label>
<input asp-for="DatabaseName" class="form-control" placeholder="Enter a database name here..." />
</div>
<div class="form-group">
<label asp-for="FolderPath"></label>
<input asp-for="FolderPath" class="form-control" />
</div>
<div class="col-3 offset-4">
<button type="submit" class="btn btn-primary">Run!</button>
</div>
</form>
@section Scripts {
<script>
$("#run-form").submit(function () {
var data = $('#run-form').serializeArray();
console.log(data);
alert($('input:hidden[name="__RequestVerificationToken"]').val());
$.ajax({
type: 'POST',
url: '/Run/Run',
contentType: 'application/json',
headers: { RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val() },
data: JSON.stringify(data),
success: function (data) {
if (data.status = "success") {
alert("Database has been updated !"); //TODO : Mettre un div vert avec un message à la place.
}
},
error: function () {
alert("An error occured 2!"); //TODO : Mettre un div rouge avec un message à la place.
}
});
//event.preventDefault();
});
</script>
}
and the controller part is :
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Run(string jsonObj)
{
//TODO : CHECK JSONOBJ
RunViewModel model = JsonSerializer.Deserialize<RunViewModel>(jsonObj);
try
{
//Call a service here...
}
catch (Exception ex)
{
//Renvoyer un message
}
return Json(model);
}
and the viewmodel is :
public class RunViewModel
{
[Required]
[Display(Name="Instance name : ")]
public string InstanceName { get; set; }
[Required]
[Display(Name="Database name : ")]
public string DatabaseName { get; set; }
[Required]
[Display(Name="SQL folder path : ")]
public string FolderPath { get; set; }
/// <summary>
/// Liste ordonnée des fichiers, regroupés par version, à lancer sur la base de données suivant la version actuelle de la base de données.
/// </summary>
public IOrderedEnumerable<IGrouping<Version, string>> SqlFilesGroupedByVersion { get; set; }
}