Reputation: 1968
As a newbie in ASP.NET Core, this is my first time trying to make an ajax call to asp.net controller method with jquery and I am finding it difficult. Below is my view form, my javascript file and my controller method;
The view form
<form id="components-form">
@Html.AntiForgeryToken();
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="entryformLabel">Payment Entries</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped" id="list-table">
<thead>
<tr>
<th>Entry</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
@foreach (var ent in ViewBag.staffEntries)
{
<tr>
<th>@ent.EntryLabel</th>
<th><input type="text" class="form-control entry" name="component[@ent.EntryId]" id="@ent.EntryId" value="@ent.EntryValue" /></th>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="update-entries-btn" class="btn btn-success"><span class="fa fa-check"></span> Update Entries</button>
</div>
</form>
The Javascript file
$(document).ready(function ()
{
var updateBtn = $("#update-entries-btn").click(function ()
{
$("#update-entries-btn").click(function () {
var token = $("[name=__RequestVerificationToken").val();
var postedValues = new FormData();
postedValues.append("__RequestVerificationToken", token);
$(".entry").each(function () {
var id = this.id;
var val = this.val;
postedValues.append(id,val);
});
var postUrl = "/staff/updatecomponents";
$.post(postUrl, postedValues, function (result) {
alert(result);
});
})
})
}
);
The controller method. I'm actually lost on how to handle the request at this point. Doint this returns null.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult updatecomponents(string posted)
{
return Json(posted);
}
I will appreciate a guide to get this working. Thank you
Upvotes: 0
Views: 6566
Reputation: 1968
After some more research, I solved this thus:
The Javascript code
$(document).ready(function ()
{
$("#update-components-btn").click(function ()
{
var token = $("[name=__RequestVerificationToken").val();
var staffId = $("[name=staffId").val();
var postedValues = {};
postedValues["__RequestVerificationToken"] = token;
postedValues.StaffId = staffId;
postedValues.StaffComponents = [];
$(".entry").each(function ()
{
var component = {};
component.StaffId = staffId;
component.EntryId = $(this).attr('id');
component.ValueAmount = Number($(this).val());
postedValues.StaffComponents.push(component);
});
var postUrl = "/staff/updatecomponents";
$.post(postUrl, postedValues, function (result)
{
var report = JSON.parse(JSON.stringify(result));
if (report.status)
{
swal("<span class=fa fa-thumbs-up", report.message, "success");
setInterval(function () { window.location.reload(true); }, 5000);
}
else
{
swal("<span class=fa fa-thumbs-down", report.message, "error");
}
});
});
}
);
I had to create a model that would emulate the expected object
public class StaffEntryUpdateModel
{
public string RequestToken { get; set; }
public string StaffId { get; set; }
public List<StaffEntry> StaffComponents { get; set; }
}
And finally the server side endpoint that receives and processes the ajax post
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult updatecomponents(StaffEntryUpdateModel postedData)
{
try
{
if (postedData.StaffComponents.Any())
{
ApplicationUser Staff = db.Users.FirstOrDefault(s => s.Id == postedData.StaffId);
if (Staff == null)
{
return new JsonResult(new { Status = false, Message = "Unknown staff" });
}
db.StaffEntries.Where(se => se.StaffId == postedData.StaffId).Delete();
foreach (var c in postedData.StaffComponents)
{
db.StaffEntries.Add(c);
}
int inserted = db.SaveChanges();
return new JsonResult(new { Status = (inserted > 0) ? true : false, Message = inserted + " components updated for staff" });
}
else
{
return new JsonResult(new { Status = false, Message = "No component sent for update for staff" });
}
}
catch (Exception e)
{
return new JsonResult(new {Status=false,Message=e.Message.ToString() });
}
}
In the process of working and reviewing the code, I had to change some items from the way it appeared in the original question but its basically the same.
I hope this helps someone looking for such solution anytime.
Thank you @Chetan Ranpariya for your attempt to help
Upvotes: 2