I'm new in web. This is my html:
<div class="modal fade" id="EditDocumentModal">
<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">Edit Vacation Types</h4>
</div>
<div class="modal-body">
<form action=#Url.Action(MVC.Admin.Admin.EditFile()) method="post" enctype="multipart/form-data" class="edit-file-form" id="Edit-File-Form">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default close-edit-document-button" data-dismiss="modal">Close</button>
<button type="button" form="Edit-File-Form" id="edit-Document-submit" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
And this is my JS:
$(document).on("click", "a.Edit-File-link", function (e) {
var id = $(this).data('id');
$.ajax({
url: '/Admin/Admin/EditFile/' + id,
cache: false
}).done(function (data) {
var div = '<div class = "checkbox-for-edit"></div>';
$('#Edit-File-Form').prepend(div);
$(".checkbox-for-edit").attr("data-id", data.documentId);
for (var i = 0; i < data.checkboxList.length; i++)
{
var checkBox = "<input type='checkbox' data-id = '" + data.checkboxList[i].Id + "' id='Edit-document-checkbox" + data.checkboxList[i].Id + "'/>" + data.checkboxList[i].Type + "<br/>";
$(checkBox).appendTo('.checkbox-for-edit');
if (data.checkboxList[i].IsSelected == true) {
$("#Edit-document-checkbox" + data.checkboxList[i].Id).prop('checked', true);
}
else {
$("#Edit-document-checkbox" + data.checkboxList[i].Id).prop('checked', false);
}
}
$('#EditDocumentModal').modal('show');
});
});
$(document).on("click", "button.close-edit-document-button", function (e) {
$(".checkbox-for-edit").remove();
});
$("#edit-Document-submit").click(function (e) {
$.ajax({
url: '/Admin/Admin/EditFile/',
type: 'POST',
data: {
documentId: $('.checkbox-for-edit').attr('data-id')
//put checkbox post logic here
},
cache: false,
dataType: "json",
success: function (data) {
}
});
});
As you can see, on click Edit-File-link I get checkboxes from the action and draw them on bootstrap modal window. This part work fine. Now I need to POST this checkboxes to my action. This is my action:
[HttpPost]
public virtual ActionResult EditFile(Guid documentId, List<VacationTypeViewModel> checkboxList)
{
throw new NotImplementedException();
}
So, Id I've posted well. But I don't know what should I do with my checkboxes on the bootstrap modal window.
First, you're not naming your checkboxes at all, so their values will never be posted. Update your checkbox creation code to add a name="checkboxList[]" attribute. Likewise, you also need to include a value="" attribute for each checkbox with something like the id you want posted back.
Second, the only thing that will ever be posted back from the checkboxes is the value you assigned, not the full VacationTypeViewModel you started off with. As a result, your action parameter should be something like List<int> checkboxList. If you need to work with the actual instances represented by the ids posted back, you'll need to requery them from the database based on the posted list of ints in your post action.
Related
This is follow up question on this (Bootstrap Modal Confirmation using ASP.Net MVC and a table)
Using MVC .NetCore, I populate a "partial" view and a Table (called _Match_StatsViewAll.cshtml under a directory of the same name of my controller Match_Stats).
It's being called from an Indexview:
public async Task<ViewResult> Match_StatsIndex(string message, string comp_id, string match_id, string team_id)//ACTION METHOD/View Results
Within that table (code below) , a list of records. Each row have a button to edit or delete. To delete a record, I need to have 4 IDs since the PK is made of those 4 keys. I was able to make it work with a javascript, however, I did not like the "confirm" display being produced. Thanks to this post, I was able to add a modal for each rows in the table and delete the record. However now, If I use the original json call to refresh the partial model (that only refresh the table), I have this screen:
Here is a Row being populated from my Model:
<td>
<div>
#{i++; }
<a onclick="showInPopup('#Url.Action("Match_StatsCreateOrEdit","Match_Stats",new {comp_id=item.Match_Stats.Comp_Id, team_id=item.Match_Stats.Team_Id,match_id=item.Match_Stats.Match_Id, match_Stat_Id=item.Match_Stats.Match_Stat_Id},Context.Request.Scheme)','Update A Stat')" class="btn btn-primary btn-xs"><i class="fas fa-pencil-alt"></i> Edit</a>
<form asp-action="Match_StatsDelete" asp-route-comp_Id="#item.Match_Stats.Comp_Id" asp-route-team_Id="#item.Match_Stats.Team_Id" asp-route-Match_Id="#item.Match_Stats.Match_Id"
asp-route-Match_Stat_Id="#item.Match_Stats.Match_Stat_Id" onsubmit="return jQueryAjaxDelete(this)" class="d-inline">
<button type="submit" class="btn btn-warning btn-xs"><i class="fas fa-trash"></i> Delete</button>
</form>
#*//add the button to launch the modal*#
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal-removeplayers_#i"><i class="fas fa-trash"></i> Delete modal</button>
<div class="modal fade" id="modal-removeplayers_#i">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Confirmation needed</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Do you really want to delete this record ?</p>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<form asp-action="Match_StatsDelete" asp-route-comp_Id="#item.Match_Stats.Comp_Id" asp-route-team_Id="#item.Match_Stats.Team_Id" asp-route-Match_Id="#item.Match_Stats.Match_Id"
asp-route-Match_Stat_Id="#item.Match_Stats.Match_Stat_Id" onsubmit="return jQueryAjaxDeleteDirect(this)" class="d-inline">
<button type="submit" class="btn btn-warning btn-xs"><i class="fas fa-trash"></i> Delete Json</button>
</form>
</div>
</div>
</div>
</div>
</div>
</td>
In my controller - calling the delete :
public async Task<IActionResult> Match_StatsDelete(string comp_id, string team_id, string match_id, string match_stat_id)
{
// Wrap the code in a try/catch block
try
{
var deleteok = _match_statsRepository.Delete(entity);
if (deleteok != null)
{
//Code Here to populate my table only since this is a partial view inside a page
return Json(new { isValid = true, html = JavaScriptConvert.RenderRazorViewToString(this, "_Match_StatsViewAll", myPartialmodelpopulated) });
}
else
{
ModelState.AddModelError("", "Could not Delete Match");
return RedirectToAction("MatchIndex", new { message = "Success", comp_id });
}
}
catch (Exception ex)
{
// Log the exception to a file.We discussed logging to a file
//......More code here for the log has been removed //
return View("Error");
}
}
Here is the Javascript:
jQueryAjaxDeleteDirect = form => {
try {
$.ajax({
type: 'POST',
url: form.action,
data: new FormData(form),
contentType: false,
processData: false,
success: function (res) {
$('#view-all').html(res.html);
$.notify('Deleted Successfully !', {
globalPostion: 'Top Center',
className: 'success'
});
},
error: function (err) {
console.log(err)
}
})
} catch (ex) {
console.log(ex)
}
//prevent default form submit event
return false;
}
The " return Json" call works fine if I use the original code (so no MODAL form - just the javascript "confirm") .
Thank you for the help!
My main idea is to show data from database and beside each row, there is an accept and reject button .onClick, the value of the button gets passed to controller and saved to database.so far so good, the issue is when I tried to add a popup modal that has input text to add a note . it should appear only when I click the reject button only. I opened the developer tools and found it passes the double of the whole number of the data rows and i don't know how to pass the id of the row I'm in, the value of the rejected button and finally the message that is going to be written to the controller. I tried to pass the modal in the reject button method in the controller but it passes as null. what am I doing wrong? is my script part is organized or even accurate after I added the ajax or not?
I appreciate any help.
my view:
#model AllmyTries.Models.fulfillmentVM
<!-- page content -->
#using (Html.BeginForm("Add_Fulfillment_Reject", "Feedback", FormMethod.Post))
{
#Html.AntiForgeryToken()
<td>
<button id="btnReject" class="btn btn-lg btn-danger" name="button" data-toggle="modal" data-target="#exampleModal" type="submit" onclick="reject(0)" value="0">Reject</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
#Html.Hidden("Status", Model._Requests[i].Status, new { id = "myEdit", value = "" })
</td>
<div class="modal fade" id="exampleModal" 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">New message</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="myform">
<div class="form-group">
<textarea class="form-control" id="message-text"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<input type="reset" value="submit" class="btn btn-success" id="finalSave" />
</div>
</div>
</div>
</div>
}
<!-- /page content -->
#section Scripts {
<script>
$('[name = "button"]').click(function () {
$('[name = "Status"]').val($('[name = "button"]').val());
})
$(document).ready(function () {
$('#finalSave').click(function () {
var dataform = $('#myform').serialize();
$.ajax({
type: 'POST',
url: '/Feedback/Add_Fulfillment_Reject',
data: dataform,
success: function () {
$('#exampleModal').modal('hide');
}
})
})
})
</script>
}
the controller:
#region fulfillment
[HttpPost]
public ActionResult Add_Fulfillment_Accept(int Request_ID, int? Status)
{
var user = db.TBL_Request.Find(Request_ID);
user.Inserted_by = Status ?? 0;
db.SaveChanges();
return RedirectToAction("Index");
}
//this is the one with the issue
[HttpPost]
public ActionResult Add_Fulfillment_Reject(fulfillmentVM vM)
{
//save the status
//save the note
db.SaveChanges();
return RedirectToAction("Index");
}
#endregion
}
Your Javascript submits only the textarea that is in the <form id="myForm"> to a controller action that is expecting a fulfillmentVM object. Change your Html.Hidden fields to Html.HiddenFor. This will bind those values on post.
Use a TextAreaFor instead of a textarea for model binding, and make sure your viewmodel has an appropriate property for it.
#Html.HiddenFor(m => m._Requests[i].Request_ID)
#Html.HiddenFor(m => m._Requests[i].Status, new { id = "myEdit", value = "" })
#Html.TextAreaFor(m => m.RejectMessage, htmlAttributes: new { #class = "form-control" })
Remove the <form id="myForm"> tags, they're unnecessary.
Keep the button as a submit button, and it will post to the Add_Fulfillment_Reject controller, passing all the bound values for your fulfillmentVM.
Where to put the form
Personally, I would put it starting right before the text box, move the hidden fields down there, too. End it right after the submit button.
#using (Html.BeginForm("Add_Fulfillment_Reject", "Feedback", FormMethod.Post))
{
#Html.HiddenFor(m => m._Requests[i].Request_ID)
#Html.HiddenFor(m => m._Requests[i].Status, new { id = "myEdit", value = "" })
#Html.TextAreaFor(m => m.RejectMessage, htmlAttributes: new { #class = "form-control" })
// rest of modal code
<input type="submit" class="btn btn-success" id="finalSave" />
} // end form
I am trying to make a bootstrap 4 modal that opens when a button is pressed inside a dynamically created element which makes an Ajax request to a form pre-populated with the data from the associated id, and then a button to save the updated information into the database.
Currently, the edit button opens a new page "editData" with the prepopulated data associated with the passed id, which then can be used to update the information upon pressing a button, and then returns to the previous page.
What are the methods that I can use to make the button open a modal on the current page that can provide the same function?
function populateData(dataInput) {
var row = $('<tr id=' + dataInput.id + '/>');
$('#table').append(row);
row.append($('<td>' + dataInput.name + '</td>'));
row.append($('<td>' + dataInput.description + '</td>'));
row.append($(
'<td><input type="submit" class="btn btn-warning" value="edit" onclick="edit(' +
dataInput.id + ')"/>'));
}
function edit(id) {
$.ajax({
type: 'GET',
url: '/getData?id=' + id,
success: function(data) {
var dataInput = JSON.parse(data)[0];
window.location = '/editData?id=' + dataInput.id;
}
})
}
Here is the getData that dynamically populates the table
app.get('/getData', function(req, res) {
var content = {};
mysql.pool.query('SELECT * FROM dataTable WHERE id=?', [req.query.id],
function(err, rows, fields) {
if (err) {
next(err);
return;
}
content.results = JSON.stringify(rows);
res.send(content.results);
});
});
And here is the editData.handler content
<div>
<form id="form">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="">
<label for="description">Description:</label>
<textarea id="description" name="description" rows="4" cols="50"></textarea>
</form>
<div class="centerButton">
<input id="submit" class="btn btn-primary" type="submit" value="Save" onclick="save()" />
</div>
</div>
This is a simple bootstrap modal.
<div class="modal fade" id="exampleModal" 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">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Now JavaScript part to make ajax request and embed data into modal.
function populateData(dataInput) {
var row = $('<tr id=' + dataInput.id + '/>');
$('#table').append(row);
row.append($('<td>' + dataInput.name + '</td>'));
row.append($('<td>' + dataInput.description + '</td>'));
//check that I have added attributes data-toggle and data-target to point example modal
row.append($(
'<td><input type="submit" data-toggle="modal" data-target="#exampleModal" class="btn btn-warning" value="edit" onclick="edit(' +
dataInput.id + ')"/>'));
}
function edit(id) {
$.ajax({
type: 'GET',
url: '/getData?id=' + id,
success: function(data) {
var dataInput = JSON.parse(data)[0];
//commented following line and adding code to embed data into modal
//window.location = '/editData?id=' + dataInput.id;
$('.modal-body').html('html that you want to show');
}
})
}
It works and here is a demo on Codepen.
Please make sure that you have include bootstrap and jquery.
I'm currently working on a Project with Phaser.js and I'm running into a problem when working on my Highscore. When the game goes into the last state called "end", it opens a Bootstrap Modal Dialog with the achieved Score and an input where you can put your name. When I hit "send" it should put the value of both inputs into the ajaxcall and send it to "/". But the inputs end up being empty, a console.log(input1 + " and " + input2); brings out nothing but the "and". I have not a clue what the problem could be since I'm not getting ANY errors. Any help is appreciated.
index.ejs:
<div class="col-md-12" id="popup">
<!-- 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">
<label for="score">Your Score:</label>
<input value="" class="form-control" id="score"><br>
<label for="name">Your Name:</label>
<input value="" class="form-control" id="name" placeholder="Choose a name for the leaderboards...">
</div>
<div class="modal-footer">
<button type="button" id="send" class="btn btn-success">Send</button>
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
ajaxcalls.js
var input1 = $('#name').val();
var input2 = $('#score').val();
$('#send').click(function(){
console.log(input1 + 'x' + input2);
$.ajax({
method: "POST",
url: "/",
data: {
Name: input1,
HScore: input2
},
success: function(data){
console.log('success');
$('#myModal').modal('hide');
}
});
});
index.js
router.post('/', function (req, res) {
var Name = req.body.Name;
var HScore = req.body.HScore;
mongoose.model('hs').create(
{
player: Name,
score: HScore
},
function (err,player) {
if(err){
res.send('Errortext!');
}
console.log('POST creating new Player: ' + player);
res.redirect('/');
});
});
mongo.js
var mongoose = require('mongoose');
var highScore = new mongoose.Schema({
player: String,
score: Number
});
mongoose.model('hs', highScore);
You just need to read values inside of click listener
$('#send').click(function(){
var input1 = $('#name').val();
var input2 = $('#score').val();
console.log(input1 + 'x' + input2);
$.ajax({
method: "POST",
url: "/",
data: {
Name: input1,
HScore: input2
},
success: function(data){
console.log('success');
$('#myModal').modal('hide');
}
});
});
I have an issue where I wanted to submit by form with javascript but obviously I have hit an issue when trying to do this and wondered if anyone could help me with the issue, more information can be found below on the issue and the code samples.
Hello. My form .submit function isn't calling when I submit my form that's added, can anyone help?
So first, the form is inside the modal:
<div class="modal fade" id="editPositionModal" role="dialog">
<div class="modal-dialog" style="width:460px;">
<!-- Modal content-->
<div class="modal-content" id="edit-position-content">
</div>
</div>
</div>
As you can see, the form has yet to be added, so I add it using a function:
function modifyPosition(businessId, positionId) {
$.ajax({
url: ajaxCallUrl + 'api/ajax/positions/' + positionId + '/get-edit-content',
type: "GET",
error: function(req, message) {
showErrorNotification('It seems something went wrong, sorry...');
},
statusCode: {
400: function (response) {
showErrorNotification(response.responseText);
},
500: function (response) {
showErrorNotification(response.responseText);
}
},
success: function(data) {
lastModifiedPositionId = positionId;
$('#edit-position-content').html(data);
$('#editPositionModal').modal('show');
},
});
}
I call the above function on the button I click to open the modal with the form on.
Heres the modal content gotten by the ajax request:
<div class="modal-header">
<button class="close" data-dismiss="modal" type="button">×</button>
<h4 class="modal-title">Creating a new position</h4>
</div>
<div class="modal-body">
<form id="save_edit_position" method="POST">
<label>Position Title</label>
<input type="text" class="form-control" style="margin-bottom:20px;" value="{{ $position->position_title }}">
<label>Position Pay</label>
<input type="text" class="form-control" style="margin-bottom:20px;" value="{{ $position->position_shift_wage }}">
<label>Position Type</label>
<select class="form-control" name="business_position_type" id="position_type_modify">
<option value="employee">Employee</option>
<option value="supervisor">Supervisor</option>
<option value="manager">Manager</option>
<option value="ownership">Ownership</option>
</select>
</div>
<div class="modal-footer">
<button class="btn btn-success" type="submit"><i class="fa fa-sign-in"></i> Save</button>
</form>
</div>
<script>
var element = document.getElementById('position_type_modify');
element.value = '{{ $position->position_type }}';
</script>
And here is the javascript handler for the form submit, on the end of the page where the modal content is included on:
$("#save_edit_position").submit(function(e) {
alert('Submit Called...');
e.preventDefault();
$.ajax({
type: "POST",
url: ajaxCallUrl + 'api/ajax/positions/' + lastModifiedPositionId + '/save-position',
data: $("#save_edit_position").serialize(),
error: function(req, message) {
showErrorNotification('It seems something went wrong, sorry...' + message);
},
statusCode: {
400: function (response) {
showErrorNotification(response.responseText);
},
500: function (response) {
showErrorNotification(response.responseText);
}
},
success: function(data)
{
var mymodal = $('#editPositionModal');
mymodal.modal('hide');
showNotification(data, updatePositionsTable(pageBusinessId)); // show response from the php script.
}
});
});
Delegate you submit event, your form is dynamically added to the page so you need event delegation to bind your event
$('body').on('submit',"#save_edit_position",function(e) {
....
or use a delegated click event
$('body').on('click',"#save_edit_position input[type='submit']",function(e) {
....
Note if you have multiple forms on the page with the same id then only the first form with the id will work ids must be unique
You should use a onSubmit="" function handler
onsubmit="functionhere();"
Your form is incorrectly structured
<div class="modal-footer">
<button class="btn btn-success" type="submit"><i class="fa fa-sign-in"></i> Save</button>
</form>
You cannot, legitimately, straddle the form tag like this and from previous experience this will likely cause problems.
You can also change your submit type to button like that and add an onclick event to a javascript function. If though your form generate dynamically, but I think this should work.
<div class="modal-footer">
<input class="btn btn-success" type="button" value="Save" onclick="_submitForm();"/>
</div>
And your js should be
function _submitForm(){
alert('Submit Called...');
$.ajax({
type: "POST",
url: ajaxCallUrl + 'api/ajax/positions/' + lastModifiedPositionId + '/save-position',
data: $("#save_edit_position").serialize(),
error: function(req, message) {
showErrorNotification('It seems something went wrong, sorry...' + message);
},
statusCode: {
400: function (response) {
showErrorNotification(response.responseText);
},
500: function (response) {
showErrorNotification(response.responseText);
}
},
success: function(data)
{
var mymodal = $('#editPositionModal');
mymodal.modal('hide');
showNotification(data, updatePositionsTable(pageBusinessId)); // show response from the php script.
}
});
}
Try
$("form.save_edit_position").submit(function(e) {...}
I have one more doubt, Can you please share exact location of javascript handler for the form submit in code!!