How to pass a parameter to a modal form using Ajax - javascript

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 );

Related

How to create bootstrap 4 confirmation modal for delete in ASP.NET MVC

I'm having trouble creating bootstrap confirmation modal in ASP.NET MVC. I've managed to successfully call modal when clicking on delete link inside view, but when I want to confirm, nothing happens.
Index View()
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CurrentGrade.GradeName)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Surname)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.CurrentGrade.GradeName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Surname)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.StudentId }) |
#Html.ActionLink("Details", "Details", new { id=item.StudentId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.StudentId }, new { #class="element", #data_toggle = "modal", #data_target = "#exampleModalCenter" })
</td>
</tr>
}
</table>
Here is modal that I'm calling:
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h6>Are you sure that you want to delete this?</h6>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-danger">Delete</button>
</div>
</div>
</div>
</div>
And finally, here is my simple js script.
$(document).ready(function () {
$('.element').click(function (e) {
$('#exampleModalCenter').modal('show');
if (confirm) {
return true;
} else {
return false;
}
});
});
UPDATE
I tried edit js code according to link that Soham provided but without any luck.
$(document).ready(function () {
$('#exampleModalCenter').on('show.bs.modal', function (e) {
$(this).find('.btn-danger').attr('href', $(e.relatedTarget).data('href'));
$('.debug-url').html('Delete URL: <strong>' + $(this).find('.btn-danger').attr('href') + '</strong>');
});
});
Maybe problem lies in #Html.ActionLink for Delete?
#Html.ActionLink("Delete", "Delete", new { id = item.StudentId }, new { #data_toggle = "modal", #data_target = "#exampleModalCenter" })
I was able to reproduce your issue and found some things required to get confirm modal popup work.
Assumed Delete action method exists:
[HttpPost]
public ActionResult Delete(int id)
{
// other stuff
return View();
}
Here are those key points:
1) Add data-id attribute to ActionLink method.
#Html.ActionLink("Delete", "Delete", new { id=item.StudentId }, new { #class="element",
#data_toggle = "modal", #data_target = "#exampleModalCenter",
#data_id = item.StudentId })
2) Add a hidden field which stores value of StudentId to delete.
#Html.Hidden("itemid", "", new { id = "itemid" })
3) Add id element to 'Delete' button in modal popup.
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="Delete" class="btn btn-danger">Delete</button>
</div>
4) Use this script inside document.ready to show modal popup and make request for 'Delete' button click:
$('.element').click(function (e) {
e.preventDefault();
$('#exampleModalCenter').modal('show');
var id = $(this).data('id');
$('#itemid').val(id);
});
$('#Delete').click(function () {
var studentId = $('#itemid').val();
$.post(#Url.Action("Delete", "Delete"), { id: studentId }, function (data) {
// do something after calling delete action method
// this alert box just an example
alert("Deleted StudentId: " + studentId);
});
$('#exampleModalCenter').modal('hide');
});
Live example: .NET Fiddle
Similar issues:
MVC Actionlink & Bootstrap Modal Submit
bootstrap modal for delete confirmation mvc
If you already have the delete action setup in the controller by entity framework, when you added a controller with actions, it should not be complicated, as all what you have to do after the user confirms the delete is to redirect to the delete action view by using simple JavaScript code and a hidden field to hold the item id to pass it in with the URL string.
The bootstrap dialog modal
<!-- Confirmation modal -->
<div class="modal fade" id="confirmdelete" tabindex="-1" role="dialog" aria-labelledby="confirmdelete" 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="confirmdelete">Action Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this record ??</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="action">Delete</button>
</div>
</div>
</div>
</div>
Hidden field to hold the item id to be deleted
Make sure it is placed inside the foreach loop
#Html.HiddenFor(c => item.ID, new { #id = "hdnItemId" })
Jquery simple code to redirect to the delete action with item id included
$(document).ready(function () {
$('#action').click(function () {
var itemId = $('#hdnItemId').val();
var actionLink = "/Banks/Delete/" + itemId;
window.location.href = actionLink;
});
});
The above answer is correct and easy but jquery code is supposed to be like this:
$(document).ready(function () {
$('#action').click(function () {
var itemId = $('#hdnItemId').val();
var actionLink = "/MyController/MyDeleteAction?id=" + itemId;
window.location.href = actionLink;
});
});

Why is the delete button on my application not working?

I made a delete button that's supposed to delete some entries from a model, but i keep getting an error that i'm not sure how to solve, I have a controller that has an IActionresult named deletelname, and everything seems logical but i just don't know why it's not working. If someone could look at the code and give me some feed back i would appreciate it very much.
The view:
#model IEnumerable<Models.pinfo>
#using Models
#foreach (var s in Model){
<h1> #s.fname #s.lname </h1> <h3> #s.comment </h3> <a class="GoDelete" href="javascript:void(0)" data-id="#s.lname">Delete</a>
<div class="modal fade" id="myModal" 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-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Deleting....</h4>
</div>
<div class="modal-body">
Are you sure to Delete this Course?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="btndelete" type="button" class="btn btn-primary">Delete</button>
</div>
</div>
</div>
</div>
}
#section scripts
{
<script>
$(document).ready(function() {
$("#btndelete").click(function () {
$('#myModal').modal('hide');
var id = $('#hfId').val();
window.location.href = '#Url.Action("deletelname","Home")/'+id;
});
$(".GoDelete").click(function () {
var id = $(this).attr("data-id");
$('#hfId').val(id);
$('#myModal').modal('show');
});
});
</script>
}
the Controller piece:
public IActionResult deletelname(pinfo pinfo)
{
var fsname = db.pinfo;
var lsname = db.pinfo;
var csomment = db.pinfo;
foreach (var fname in fsname)
{
db.Remove(fname);
}
foreach (var lname in lsname){
db.Remove(lname);
}
return View("Contact", "Home");
}
here is the error i get when i press the delete button:
The error message is because you are passing the string "Home" as the model for the view "Contact". The view is expecting an enumerable object of type Model.pinfo
try passing the pinfo object back out of the controller when rendering the view. I'm not sure that will do what you want but it seems to be what you are looking for.
public IActionResult deletelname(pinfo pinfo)
{
var fsname = db.pinfo;
var lsname = db.pinfo;
var csomment = db.pinfo;
foreach (var fname in fsname)
{
db.Remove(fname);
}
foreach (var lname in lsname){
db.Remove(lname);
}
return Contact();
}
Javascript is not correct either
$("#btndelete").click(function () {
$.ajax({
url: '#Url.Action("deletelname","Home")',
method: 'POST',
data: { pinfo: $('#hfId').val() },
success: function (response) {
// this code gets run after the request is successful
// based on the controller method that we have written, the response
// should be all of the "Contact" view html re-rendered.
console.log(response);
//if there is an error you will probably not want to close the modal
// so only close if it is successful
$('#myModal').modal('hide');
},
error: function (response) {
//runs if there is an error
console.log(response);
}
});
});

Struts2 action not being called on page refresh

I'm making a CRUD application for a school project, where there is a list of 'lesson groups', which you can add or remove.
I have a bootstrap modal that looks like this, where you can input a lesson group name and press a button to submit it:
<div class="modal fade" id="lessonGroupAddModal" tabindex="-1" role="dialog"
aria-labelledby="lessonGroupAddModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="lessonGroupAddModalLabel">Les groep toevoegen</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form class="addLessonGroupForm" role="form">
<div class="form-group">
<label for="lessonGroupName-input" class="col-2 col-form-label">Naam</label>
<div class="col-10">
<input class="form-control" type="text" value="" id="lessonGroupName-input">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Sluiten</button>
<button id="addLessonGroupButton" type="button" class="btn btn-primary">Toevoegen</button>
</div>
</div>
</div>
</div>
The button works by a JavaScript AJAX post request, this looks like this:
$("#addLessonGroupButton").on("click", function() {
if($("input[type=text]#lessonGroupName-input").val()) {
$.ajax({
type: 'POST',
url:'lessongroup/add.action',
dataType: 'json',
data : "lessonGroupName="+$("input[type=text]#lessonGroupName-input").val(),
});
}
location.reload();
});
The action method i'm using for this looks like this:
public String addLessonGroup() {
if (this.lessonGroupName == null || this.lessonGroupName.equals("")) {
return ERROR;
}
LessonGroup previousLessonGroup = this.getLessonGroups().last();
TestDAOLessonGroup.getInstance().create(new LessonGroup(previousLessonGroup.getId() + 1, lessonGroupName));
System.out.println("added lesson group with name " + lessonGroupName);
return SUCCESS;
}
The TestDAOLessonGroup is a singleton which saves that objects, i'm 100% sure the object is only getting made once.
The execute method of the controller looks like this:
public String execute() {
if (lessonGroups == null) {
lessonGroups = new TreeSet<>();
}
lessonGroups.clear();
lessonGroups.addAll(TestDAOLessonGroup.getInstance().getLessongroups());
return SUCCESS;
}
This puts the most recent lesson groups into the variable, which i am getting in the view.
My struts.xml action mapping looks like this:
<action name="lessongroup" class="employeemanagement.LessonGroupListingAction"
method="execute">
<result name="success">index.jsp</result>
</action>
I'm 100% sure this mapping works, and the lesson grouups are getting loaded in the view.
The problem is that when you add a new lesson group to the DAO via the post request, and it reloads the page by the location.reload(); statement, it doesn't call up the action the first time. When I add another lesson group, it works just fine.
How can I make it so that the Action would get called on the first page refresh? Am I using the right approach for this?
The url is not mapped to the action. You should add
<action name="add" class="employeemanagement.LessonGroupListingAction"
method="add">
<result type="json"/>
</action>
The json plugin is required to return json type result.
This action should be mapped to the url in ajax call
$("#addLessonGroupButton").on("click", function() {
if($("input[type=text]#lessonGroupName-input").val()) {
$.ajax({
type: 'POST',
url:'add.action',
dataType: 'json',
data : "lessonGroupName="+$("input[type=text]#lessonGroupName-input").val(),
success: function(data) {
console.log(JSON.stringify(data));
}
});
}
});

Boostrap modal not loading when wired using jquery

I have the following link and I'm trying to load a bootstrap modal when its clicked but the javascript function doesnt seem to be firing. Instead of the view loading inside a modal, its loading as a new page?
#*this is the modal definition*#
<div class="modal hide fade in" id="report-summary">
<div id="report-summary-container"></div>
</div>
<script >
$('a.js-report-summary').click(function (e) {
var url = $(this).attr('href'); // the url to the controller
e.preventDefault();
$.get(url, function (data) {
$('#report-summary-container').html(data);
$('#report-summary').modal('show');
});
});
</script>
public ActionResult ReportSummary()
{
// some actions
return PartialView("ReportSummary", viewmodel)
}
// Report summary view which contains modal
<div class="modal-dialog" role="document">
<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">#ViewBag.FormName - Analysis</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">
Close</button>
</div>
</div>
</div>
There are no errors showing in the console either so why isn't the jquery function firing?
in your click function, add parameter e this will stand for event
then in the function itself add e.preventDefault() This will stop the refreshing effect.
on your controller method try
public ViewResult ReportSummary()
{
// some actions
if(Request.IsAjaxRequest())
return PartialView("ReportSummary", viewmodel);
else
return View("ReportSummary", viewmodel);
}
on your view
$('#exampleModal').on('show.bs.modal', function (event) {//give your model wrapper an id
//do some ajax and get html
$.ajax({
url:'',
success:function(data){
$('#report-summary-container').html(data);
}
});
})
on your anchor tag, add data-toggle="modal" data-target="#exampleModal"
if you dont want to use bootstrap events trigger your modal with
$('#myModal').modal('show')

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