Calling a MVC controller using jQuery and ajax - javascript

Hello I am trying to call a method with parameters in my controller using ajax and jquery
Controller:
[HttpPost("{Id}")]
public ActionResult PostComment(int Id, ShowViewModel model)
{
}
View:
I have a button called AddComment, when clicked it should open a modal popup which asks for confirmation to save
<form id="addCommentForm" asp-action="postcomment" enctype="multipart/form-data">
<button id="addCommentButton" class="btn btn-primary">
<i class="fa fa-search"></i> Add comment
</button>`
<div class="modal fade" id="saveConfirmationDialog" tabindex="-1" role="dialog" aria-labelledby="saveConfirmationDialogTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="saveConfirmationDialogTitle">Post selective exchange comment</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Do you want to post a comment?
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">
<i class="fa fa-envelope-open"></i> Post selective exchange comment
</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">
<i class="fa fa-ban"></i> Close
</button>
</div>
</div>
</div>
</div>
</form>
Javascript:
ControllerName.View.Properties.controllerViewUrl = $("#controllerViewUrl").val();
$(document).ready(function () {
ControllerName.View.Validation.initialize();
ControllerName.View.Initialize.addCommentButton();
});
ControllerName.View.Initialize = {}
ControllerName.View.Initialize.addCommentButton = function () {
$('#addCommentButton').click(function (event) {
event.preventDefault();
if ($('#addCommentForm').valid()) {
$("#saveConfirmationDialog").modal('show');
}
});
}
ControllerName.View.Validation = {}
ControllerName.View.Validation.initialize = function () {
$("#addCommentForm").validate();
}
ControllerName.View.Ajax = {}
ControllerName.View.Ajax.postComment = function (successCallback) {
var url = ControllerName.View.Properties.controllerViewUrl + '/PostComment'+<<parameter>>;
}
My Controller method is not getting called, what am I doing wrong?
I also need to pass a Id as parameter
Please help, Thanks in advance

A simple example
HTML CODE
<button id="saveButton" type="button" data-toggle="modal" data-target="#saveConfirmationDialog" class="btn btn-labeled btn-danger" style="display:none;">Save Data</button>
<div id="saveConfirmationDialog" class="modal fade" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 id="modal-title" class="modal-title">Post selective exchange comment</h4>
</div>
<div class="modal-body">
Do you want to post a comment?
</div>
<div class="modal-footer">
<div id="formDiv">
<button id="sender" type="submit" class="btn btn-success"><i class="fa fa-envelope-open"></i> Post selective exchange comment</button>
<button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-ban"></i> Close</button>
</div>
<div id="loadingPanel" style="display:none;">Loading...</div>
</div>
</div>
</div>
</div>
JS CODE
<script type="text/javascript">
$('#sender').click(function () {
PostDataToController();
});
function PostDataToController(action) {
$('#formDiv').hide();
$('#loadingPanel').show();
// create form data
var formData = new FormData();
formData.append("YourParameter", $('#YourValue').val());
// Write here your parameters what you need
// do post
$.ajax({
type: "POST",
url: "/localhost:8080/InsertComment",
enctype: "multipart/form-data",
cache: false,
contentType: false,
processData: false,
data: formData,
success: function (d) {
$('#formDiv').show();
$('#loadingPanel').hide();
if (d.result == "ok") {
/*Your success operations*/
}
else {
//alert(d.msg);
/*Your custom error operations*/
}
},
error: function (xhr, textStatus, errorThrown) {
/*Your error operations*/
//alert(xhr);
$('#formDiv').show();
$('#loadingPanel').hide();
}
});
}
</script>
MVC CODE
[HttpPost]
public ActionResult InsertComment(int Id, ShowViewModel model)
{
if (ModelState.IsValid)
{
// insert
// Yor save method is here
if (!isSuccess()) // your process not succeeded
{
// error
return Json(new { result = "no", msg = /*your error message*/ });
}
//succeeded
return Json(new { result = "ok" });
}
else
{
// error
string error = ModelState.Values.FirstOrDefault(f => f.Errors.Count > 0).Errors.FirstOrDefault().ErrorMessage;
return Json(new { result = "no", msg = error });
}
}

Related

Getting a 405 error when trying to call Delete Modal Confirmation action (Asp.Net Core 6 javascript)

I'm working on my first Asp.Net Core application, and am struggling with modals, Razor pages and route mapping are completely new things for me, and javascript is a pretty old thing for me. I'm trying to create a delete modal that can be used for any object (my test object is of type Employee). Maybe this isn't possible, I'm not sure. My modal displays fine, but when I click to call my DeletePOST method I get a 405 error. The URL in question returns as https://localhost:44313/Employee/DeletePOST/1 (when the employee with id = 1 is selected). The "warning" message that I get in the console is
(index):6789 crbug/1173575, non-JS module files deprecated.(anonymous) # (index):6789.
Here is the applicable code from View.Employee.Index
<tbody>
#foreach (var employee in Model)
{
<tr id="row_#employee.Id">
<td>#employee.Name</td>
<td>#employee.Phone</td>
<td>#employee.Email</td>
<td>#employee.Address</td>
<td>#employee.Role</td>
<td>#employee.Availability</td>
<td class="w-100 btn-group" role="group">
<a asp-controller="Employee" asp-action="Edit" asp-route-id="#employee.Id"
class="btn btn-primary mx-2"> <i class="bi bi-pencil-square"></i> Edit</a>
<!--delete modal confirmation button-->
<a class="btn btn-danger delete" id="#delete" data-id="#employee.Id"
data-url ="#Url.Action("DeletePOST","Employee")/"
data-body-message= "Are you sure you want to delete this employee?">
<i class="bi bi-trash"></i> Delete</a>
</td>
</tr>
}
</tbody>
Code from wwwroot.js.delete.js
$((function () {
var target;
var pathToDelete;
var id;
$('body').append(`
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-bs-dismiss="modal"
aria-label="Close"><span aria-hidden="true">×</span> </button>
<h4 class="modal-title" id="myModalLabel">Warning</h4>
</div>
<div class="modal-body delete-modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal"
id="cancel-delete">Cancel</button>
<button type="submit" class="btn btn-danger"
id="confirm-delete">Delete</button>
</div>
</div>
</div>
</div>`);
//Delete Action
$(".delete").on('click', (e) => {
e.preventDefault();
target = e.target;
id = $(target).data('id');
pathToDelete = $(target).data('url');
var bodyMessage = $(target).data('body-message');
pathToDelete = pathToDelete + id;
$(".delete-modal-body").text(bodyMessage);
$("#deleteModal").modal('show');
});
$("#confirm-delete").on('click', () => {
window.location.href = pathToDelete; //suspect issue
});
}()));
Code from Controllers.EmployeeController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DeletePOST(int? id)
{
var selectedEmployee = _db.Employees.Find(id);
if (selectedEmployee == null)
{
return NotFound();
}
_db.Employees.Remove(selectedEmployee);
_db.SaveChanges();
return RedirectToAction("Index"); //suspect issue
}
```
If you want to call DeletePOST in js,you can try to use ajax,since you need to add AntiForgeryToken to the request,you also need to add #Html.AntiForgoryTokento your view:
view:
<tbody>
#foreach (var employee in Model)
{
<tr id="row_#employee.Id">
<td>#employee.Name</td>
<td>#employee.Phone</td>
<td>#employee.Email</td>
<td>#employee.Address</td>
<td>#employee.Role</td>
<td>#employee.Availability</td>
<td class="w-100 btn-group" role="group">
<a asp-controller="Employee" asp-action="Edit" asp-route-id="#employee.Id"
class="btn btn-primary mx-2"> <i class="bi bi-pencil-square"></i> Edit</a>
<!--delete modal confirmation button-->
<a class="btn btn-danger delete" id="#delete" data-id="#employee.Id"
data-url ="#Url.Action("DeletePOST","Employee")/"
data-body-message= "Are you sure you want to delete this employee?">
<i class="bi bi-trash"></i> Delete</a>
</td>
</tr>
}
</tbody>
#Html.AntiForgoryToken
js:
$("#confirm-delete").on('click', () => {
$.ajax({
type: "POST",
url: pathToDelete,
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
}).done(function (result) {
//redirect to Index here
window.location.href="Index";
});
});
Or you can remove the following code in Controller:
[HttpPost]
[ValidateAntiForgeryToken]

How do I remove a .html in javascript?

Hello guys I need help to remove a span after being successful in ajax.
I am inserting a loading when pressing, the save button so that the user does not keep pressing several times and ends up passing the same item several times, but after success it returns without the old way
follows an excerpt from the code where I'm using this function
$('#btn_salvar_consultor').prop("disabled", true);
// Adicionar loading no botão
$('#btn_salvar_consultor').html(
`<span id="loading_consultor" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>`
);
var Consultor = $('#consultor').val();
var justificativaconsultor = $('#justificativaconsultor').val();
$.ajax({
url: '#Url.Action("AdicionarConsultor", "Oportunidade")',
data: {
id_usuario_responsavel: Consultor,
id_oportunidade: id_oportunidade,
justificativaconsultor: justificativaconsultor
},
type: 'POST',
success: function(data) {
$('#AddConsutlorResponsavel').modal('hide');
$.ajax({
url: '#Url.Action("_PartialOportunidadeTimeline", "Oportunidade")',
data: {
id_oportunidade: id_oportunidade
},
type: 'POST',
success: function(data) {
$('#btn_salvar_consultor').prop("disabled", false);
$('#loading_consultor').remove()
$('#consultor').val("0");
$('#justificativaconsultor').val("");
$("#partinal_container-fluid").html(data);
}
});
},
error: function(xhr, status, error) {
swal({
title: 'Ops!',
text: error,
icon: 'error',
timer: 10000,
button: 'OK!'
});
$('#btn_salvar_consultor').prop("disabled", false);
$('#loading_consultor').remove();
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="modal fade" id="AddConsutlorResponsavel" tabindex="-1" role="dialog" aria-labelledby="TituloModalCentralizado" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content" style="box-shadow: 0 0 1em black; border:solid 1px">
<div class="modal-header">
<h5 class="modal-title" id="TituloModalCentralizado">Selecione o consultor</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="partinal_container-fluid" class="modal-body">
<div class="row">
<select id="consultor" class="form-control" data-val="true" name="consultor">
<option value="0">[Selecione...]</option>
#foreach (var item in ViewBag.Consultor) {
<option value="#item.UsuarioId">#item.NomeCompleto</option>
}
</select>
</div>
<div class="row">
<label class="col-form-label">Justificativa</label>
<textarea id="justificativaconsultor" class="form-control"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
<button type="button" class="btn btn-primary" id="btn_salvar_consultor" onclick="AddConsultor()">Salvar</button>
</div>
</div>
</div>
</div>
Solution
I realized that when I remove the span it removes the text, it follows the correction after success or error in ajax.
$('#btn_salvar_consultor').prop("disabled", false).text("Salvar");
instead of
$('#btn_salvar_consultor').prop("disabled", false);

How to pass a parameter to a modal form using Ajax

I have a razor page that displays a list of expenses for the Report selected. I have an "Add Expense" button on the page that brings up a modal. The modal is a partial View of the form. What i need to do is pass the ExpenseId to the modal. I can get the Id from the url like this
#{ var expenseId = Request.Url.Segments[3]; }
the button currently looks like this
<button type="button" data-toggle="modal" data-target="#expenseModal_#expenseId" data-id="#expenseId" class="btn btn-primary" id="addExpenses">
Add Expense
</button>
There are a few things in this that i do not know if i even need them. I was trying different things.
Modal
<!-- MODAL -->
<div class="modal fade" id="expenseModal_#expenseId" tabindex="-1" role="dialog" aria-labelledby="expenseModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="expenseModalLabel"> Expences </h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div> <!-- MODEL HEADER-->
<div class="modal-body">
</div> <!-- MODAL BODY-->
</div>
</div>
Javascript
<script type="text/javascript">
$(document).ready(function () {
$("#addExpenses").click(function () {
$(".modal-body").html('');
$.ajax({
type: 'GET',
url: '#Url.Action("_ExpenseForm", "Admin")',
data: { type: $(this).attr("data-type") },
success: function (response) {
$(".modal-body").html(response);
$("#expenseModal").modal('show');
},
error: function () {
alert("Something went wrong");
}
});
});
});
</script>
The expense Id has to be inserted in the form so that when it is saved it saves it to the correct Expense report.
Controller actions
ExpensesDataAcessLayer objexpense = new ExpensesDataAcessLayer();
public ActionResult ExpenseReports()
{
return View(db.ExpenseReports.ToList());
}
public ActionResult Expenses(int ExpenseId)
{
return View(db.Expenses.Where(x => x.ExpenseId == ExpenseId).ToList());
}
public ActionResult _ExpenseForm()
{
CustomerEntities customerEntities = new CustomerEntities();
List<SelectListItem> categoryItem = new List<SelectListItem>();
ExpensesViewModel casModel = new ExpensesViewModel();
List<ExpenseTypes> expensetypes = customerEntities.ExpenseType.ToList();
expensetypes.ForEach(x =>
{
categoryItem.Add(new SelectListItem { Text = x.CategoryItem, Value = x.ItemCategoryId.ToString() });
});
casModel.ExpenseTypes = categoryItem;
return View(casModel);
}
Thanks for your help!
You can store expenseId into hidden field, like this
<input id="expenseId" name="expenseId" type="hidden" value="#Request.Url.Segments[3]">
Then you can get like this
$("#addExpenses").click(function () {
var expenseId = $("#expenseId").val();
// after code here
Updated
You can get expenseId like this
var expenseId = $(this).attr("data-id")
Then you can assign it to hidden field or anywhere in Model, Like this
<!-adding aditional input into HTML in MODEL-!>
<input id="expenseId" name="expenseId" type="hidden" value="">
<!- Javascript-!>
var expenseId = $(this).attr("data-id")
expenseId.val(expenseId );

How to popup(open) a bootstrap modal on ajax success

I have a JSP page,say xyz.jsp. I have a button called "send Mail" that has it's onclick() property set to a script function called sendMail(). Sending mail includes sending html data to the controller for generating PDF for which I am using Ajax. Now after the mail is sent successfully ,i want to show a pop-up indicating success. So on Ajax success i want to trigger the popup.
I am using bootstrap modal for popup.
This is my code for button and modal:
<div id="reportbuttons">
<button type="button" class="btn bg-red waves-effect" onclick="convertToPdf()" style="margin-right: 5px;float: right; margin-top: -8px">Download</button>
<button type="button" class="btn bg-red waves-effect" onclick="sendMail()" style="margin-right: 5px;float: right; margin-top: -8px">Send Mail</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-
dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data
dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
And, this is my script:
<script>
function sendMail() {
let doc = new jsPDF('p','pt','a4');
doc.setProperties({
title: 'PDF Document',
subject: 'subject',
author: 'ABC',
keywords: 'generated, javascript, web 2.0, ajax',
creator: 'XYZ'
});
//document.getElementById('reportbuttons').remove();
document.getElementById('reportbuttons').style.display ="none";
doc.addHTML(document.body, function() {
var data = doc.output('datauristring');
var reqJson = {};
reqJson.machineId = "<%=machineId%>";
reqJson.monthYear = "<%=monthYear%>";
reqJson.data = data;
$.ajax(
{
url : "sendMail/",
type: "POST",
dataType: 'json',
data : JSON.stringify(reqJson),
contentType: "application/json",
success:function(data)
{
$("#myModal").modal();
alert('mail sent successfully');
document.getElementById('reportbuttons').style.display ="block";
},
error: function(data)
{
document.getElementById('reportbuttons').style.display ="block";
}
});
});
}
</script>
I want to show the bootstrap modal popup after the mail is succesfully sent or in other words on Ajax success.

Ajax post request not passing through ID

I am currently dynamically setting data attributes on widgets which are ID's through javascript, I then get the attribute when I go to delete the widget so I can remove the widget entry from the database. I have stepped through the code in firebug and it seems to get the widgetID fine, but when I go to make an ajax post request it does not seem to append the ID for the routing value.
Here is the modal:
div class="modal fade" id="deleteWidgetModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<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="myModalLabel">Delete widget?</h4><!--add depending on which panel you have clicked-->
</div>
<div class="modal-body" id="myModalBody">
<!--Depending on which panel insert content-->
#using (Html.BeginForm("DeleteWidgetConfirmed", "Dashboard", FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
#Html.AntiForgeryToken();
<div class="form-horizontal">
Do you wish to delete this widget?
<div class="form-group">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" value="DeleteWidgetConfirmed" class="btn btn-danger btn-ok" id="delete-widget">Delete</button>
</div>
</div>
</div>
}
</div>
</div>
</div>
Here is my rendered HTML for the widget where the widgetID is set:
<div class="panel panel-default" draggable="true" data-widgetid="4">
<div class="panel-heading">
<div class="panel-body">
I then try to make a post:
$(document).ready(function () {
$('#columns').on('click', '.glyphicon.glyphicon-trash', function (event) {
var panel = this;
//get id here
//toggle the modal
$('#deleteWidgetModal').modal('show');
var widgetID = $(this).closest('.panel.panel-default').attr('data-widgetid');
document.getElementById('delete-widget').onclick = function (event) {
event.stopPropagation();
//anti forgery token
var form = $('#__AjaxAntiForgeryForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
var URL = '/Dashboard/DeleteWidgetConfirmed';
console.log(widgetID + " test1");
//we make an ajax call to the controller on click
$.ajax({
url: URL,
data: {
__RequestVerificationToken: token,
id: widgetID
},
type: 'POST',
dataType: 'json',
success: function(data){
var parentElement = $(panel).closest(".col-md-4.column");
var targetElement = $(panel).closest(".panel.panel-default");
targetElement.remove();
//parentElement.addClass("expand-panel");
checkEmptyPanelContainers();
$('#deleteWidgetModal').modal('hide');
},
error: function (response) {
console.log(widgetID + " ERROR");
}
})
}
})
});
and here is my HTTP POST request which I got from the NET panel in firebug:
/Dashboard/DeleteWidgetConfirmed
and here is my controller:
// POST: DashboardModels/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteWidgetConfirmed(int? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DashboardModel dashboardModel = db.dashboards.Find(id);
db.dashboards.Remove(dashboardModel);
db.SaveChanges();
return new EmptyResult();
}
Here is the parameter being passed through with my response:
http://gyazo.com/696b684cc3650dd24731ad8ecdce1447

Categories

Resources