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
Related
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 );
I got a problem with foreach loop. What am i trying to do is get data (JsonResult) from action in controller. Get get songs for each album.
public JsonResult SongListByAlbum(int albumID)
{
var songs = (from song in Song.GetSongList()
join album in Album.GetAlbumList()
on song.AlbumID equals album.AlbumID
where (albumID == album.AlbumID)
select song).ToList();
return Json(songs,JsonRequestBehavior.AllowGet);
}
Then put them into view, for album get list of songs and show them as modals
There is my view:
#foreach (var item in Model.Albums){
<button id="#item.AlbumID" type="button" class="btn btn-primary myModals" data-toggle="modal" data-target="#exampleModal-#item.AlbumID">
Show
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal-#item.AlbumID" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel-#item.AlbumID" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel-#item.AlbumID">#item.AlbumName #item.Year, #item.BandName</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="parent" class="modal-body">
</div>
<div class="modal-footer">
<button id="closeModal"type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
}
And there is a script, where I get songs for each album.
<script>
$(".myModals").on("click", function () {
var Id = $(this).attr('id');
alert(Id);
$.ajax({
type: "GET",
url: '#Url.RouteUrl(new{ action= "SongListByAlbum", controller="Default"})',
data: {albumID:Id},
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
for (var i in result) {
$('#parent').append('<p class="toRemove">' + result[i].SongName + '</p>');
}
},
error: function (response) {
alert('error');
}
});
});
</script>
The problem is : when i click on the first modal button everything is fine, i get what i want to. But when i click on the second one i got empty modal. Then when i click again on the first one i got data from previous click and penultimate. Image: enter image description here
To avoid multiple <div id="parent"> elements, you should probably assign the Id the same way you do for the buttons. Like <div id="parent-#item.AlbumID">. Then in your ajax call reference the correct div. $('#parent-' + Id).
Not sure if that is your only probably, but might get you closer.
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.
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 });
}
}
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);
}
});
});