How to prevent HTML rendering when not visible data-binding - html

I have this code to show an alert banner if isBannerVisible is true. But if the value is false the banner still renders for a couple of seconds and then goes away. I have no idea how to prevent this from happening. I tried adding <div style="display:none" data-bind="visible: true"> before it and it doesn't show on isBannerVisible = true or false.
<div data-requisite="mybiz.businesscenter.infobannercomponent" data-bind="if: shouldInitialize">
<div class="alert alert-info alert-dismissable" data-bind="visible: isBannerVisible()">
<button type="button" class="close" data-dismiss="alert" data-bind="click: bannerClose"
aria-hidden="true">
×
</button>
JS.....
var InfoBannerViewModel = function ($el) {
var self = this;
.....
self.isBannerVisible = ko.observable((!dataStore.getItem('isBannerVisible') ? true : dataStore.getItem('isBannerVisible')));
.......
};
var _init = function ($el) {
var infoBannerViewModel = new InfoBannerViewModel($el);
app.bind(infoBannerViewModel, $el);
};
return {
init: _init
};
});

I do agree with #super cool answer in comment above, and here is the example of how to do it:
<div data-requisite="mybiz.businesscenter.infobannercomponent" data-bind="if: shouldInitialize">
<!-- ko if: isBannerVisible() -->
<div class="alert alert-info alert-dismissable">
<button type="button" class="close" data-dismiss="alert" data-bind="click: bannerClose"
aria-hidden="true">
×
</button>
</div>
<!-- /ko -->
</div>

Related

Modal ajax.form validation ASP.NET MVC, error message not showing, modal not closing after succesful submit

i'm new to the ASP.net and i get easilly confused when jquery and Ajax get in the middle of a code.
I have a popup bootstrap Modal that show when i click on a button, the Modal contains an Ajax.form that allows me to create projects, i'm using HTML.validation to check if my form is filled correctly. I have two main problems :
When I enter valid informations in my form and i submit the form, the project is created succesfully but the Modal doesn't close automaticlly.
When i enter non-valid informations when i submit no message error apear, nonetheless when I close the modal and open it again, the errors apear.
I need your help to :
Close the modal once the submit form is valid.
Have the error message show in my modal form.
*This is a part of my main view :
enter code here
<!--validation script -->
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<!-- Button trigger modal -->
<div>
<div>
<a class="btn btn-red ms-auto my-auto h-50"
href="#Url.Action("createProject", "ProjectSelection")" title="Nouveau projet"
data-bs-toggle="modal" data-bs-target="#Modal_NewProject"
ajax-target-id="Body_NewProject" data-bs-loader="Loader_NewProject">
<i class="feather-16" data-feather="plus"></i>
Créer projet
</a>
</div>
</div>
<br />
<!-- Modal View -->
<div class="modal fade" id="Modal_NewProject" tabindex="-1"
aria-labelledby="Label_NewProject" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="Label_NewProject">
Créer un Projet</h5>
<button type="button" class="btn-close"
data-bs-dismiss="modal" aria-label="Close"></button>
</div>
#using (Ajax.BeginForm("createProjectPost",
"ProjectSelection", new AjaxOptions { HttpMethod = "POST",
UpdateTargetId = "Body_NewProject" }, new { id = "projectForm" }))
{
<div id="Body_NewProject">
<div class="spinner-border" role="status"
id="Loader_NewProject">
<span class="visually-hidden">Loading...</span>
</div>
<!-- partial view "createProject" -->
</div>
}
</div>
</div>
</div>
<!---->
*And this is my partial view that containts the elements of the form
<div class="modal-body" id="frmProject">
<div class="input-group mb-3" id="">
#Html.DropDownListFor(m => m.Project.Domain,
new SelectList(Model.Domains, "IdDomain", "Name"),"Selectionner un domaine",
new { #class = "w-100", #id = "DomainSelection" })
#Html.ValidationMessageFor(m => m.Project.Domain, null,
new { style = "color: red;" })
</div>
<div class="input-group mb-3 mb-3 " id="teamSelection">
#Html.DropDownListFor(m => m.Project.Teams,
new SelectList(Model.Teams.Select(teamElement => teamElement.Name).ToList()),
"Selectionner une équipe", new { #class = "w-100" })
#Html.ValidationMessageFor(m => m.Project.Teams, null,
new { style = "color: red;" })
</div>
<div class="form-floating mb-3">
<input class="form-control " data-val-required="Le champ Projet est requis."
id="Project.Name" name="Project.Name" type="text" value="">
<label for="Project.Name" class="">Nom du projet</label>
#Html.ValidationMessageFor(m => m.Project.Name, null,
new { style = "color: red;" })
</div>
</div>
<div class="modal-footer mb-0">
<div class="panel-footer">
<button class="btn btn-secondary" data-bs-dismiss="modal"
type="button">Annuler</button>
<button type="submit" form="projectForm"
class="btn btn-red">Valider</button>
<div class="col-xs-10" id="lblstatus"></div>
</div>
</div>
*This is my Controller code
public ActionResult createProject()
{
//initialization code
return PartialView();
}
[HttpPost]
[ValidateAntiForgeryToken]
[HandleError]
public ActionResult createProjectPost(Project project)
{
#region Variable verification
if (!ModelState.IsValid)
{
Session["Error"] = true;
if (project.Domain == null)
{
Session["DomainError"] = true;
}
if (project.Teams == null)
{
Session["TeamError"] = true;
}
if (project.Name == null)
{
Session["NameError"] = true;
}
ViewData["project"] = "create";
//return View("ProjectSelectionPage");
return PartialView(project);
}
#endregion
#region Initialisation
//initilization code
#endregion
#region Check possible copy of the project
if (projectDB.Exist(project.Name))
{
//Check that this project doesn't exist in the database
//Create a session variable that will trigger an error message
Session["Error"] = true;
Session["NameCopy"] = true;
ViewData["project"] = "create";
return PartialView(project);
}
#endregion
#region Project to database and generate name
//Add the project to the database
#endregion
return PartialView();
}
It's been several days since i'm searching for an answer, i either missed one or didn't use it correctly.
enter image description here
Thank you

how can i use this modal within my foreach loop? (HTML / Razor)

I have a button that when clicked should open a modal with a confirmation stating whether the user would like to delete the selected line or not, hence on the modal, there is a 'Yes' and 'No' option. With the 'Yes' button carrying out the onclick function which is responsible for deleting the line item (These operations take place within my controller and are not part of this question). To provide a bit of background, originally the onclick function had been part of my button, which now opens the modal, and this worked perfectly as intended. However, now that button serves only one purpose, and that is to open the modal. Within the modal, the onclick function has now been moved to the 'Yes' button. But now, this onclick function does not work as it use to, and i believe this is something to do with the foreach loop that all of this is in.
Below is the code for the button and modal:
#Model.CategoryList.result
#if (Model.CategoryList.result == "")
{
int count = 0;
foreach (String dataLine in Model.CategoryList.userData)
{
string countString = count.ToString();
string target = "dataLine" + countString;
string trigger = "#" + target;
string deleteHolder = dataLine.Split(Model.CategoryList.delimiterChar)[0];
<p>
<a data-toggle="collapse" href="#trigger" role="button" aria-expanded="false" aria-controls="collapseExample">
#dataLine.Split(Model.CategoryList.delimiterChar)[0]
</a>
<button class="btn" data-toggle="modal" data-target="#deleteHolder" id="#dataLine.Split(Model.CategoryList.delimiterChar)[1]"></button>
</p>
<div class="modal" id="deleteHolder" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">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">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="location.href = '#Url.Action("DeleteCategoryLine", "Index", new { id = dataLine.Split(Model.CategoryList.delimiterChar)[1] })'">Yes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
count++;
}
}
The problem i have is: The onclick event deletes a line in the text file, that is why i have count, trigger and target to identify WHICH line to delete. However, after moving the onclick event to my modal, it will always delete the first line in the text file. I am unsure as to why this happens? Do i not understand the implications a modal presents?
My controller Action:
public ActionResult DeleteCategoryLine(int id, string changedItem)
{
string strFilePath = "~/App_Data/Category.txt";
string strSearchText = id.ToString();
string strOldText;
string n = changedItem;
StreamReader sr = System.IO.File.OpenText(Server.MapPath(strFilePath));
while ((strOldText = sr.ReadLine()) != null)
{
string[] x = strOldText.Split(',');
if (!x[1].Contains(strSearchText))
{
n += strOldText + Environment.NewLine;
}
}
sr.Close();
System.IO.File.WriteAllText(Server.MapPath(strFilePath), n);
}
As per our chat, the answer to this issue was that the ID of the modal was not unique and so it was creating the first and that's that.
I advised OP to suffix the modal with a unique ID
deleteHolder_#dataLine.Split(Model.CategoryList.delimiterChar)[1]
and it seems to have worked.

How to get Modal to work past page 1 for datatables and Bootstrap 4

I know I dont have code listed, but I still wanted to pose the question until I can get some code up.
Does boostrap 4 modals work on datatables on pages past 1?
It is not working for me. When I search or go to a different page of the table, the modal doesnt pop up.
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Asset ID</th>
</tr>
</thead>
<tbody>
<tr>
<td><button style='background-color: Transparent;border: none' data-id='16' class='asset_quick_view'><font color='blue'>A0016A</font></button></td>
</tr>
.... repeat for over 10 times to get more than 1 page
</tbody>
<tfoot>
<tr>
<th>Asset ID</th>
</tr>
</tfoot>
</table>
<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">Asset Info</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>
<script>
$(document).ready( function() {
$('.asset_quick_view').click( function() {
var asset_id = $(this).data('id');
// AJAX
$.ajax( {
url: 'get_asset_info.php',
type: 'post',
data: {asset_id: asset_id},
success: function( response ) {
// Add response in modal body
$('.modal-body').html(response);
// Display Modal
$('#exampleModal').modal('show');
}
});
});
});
</script>
Try to use an delegated event handler on the table's tbody as shown in the datatables example. As the table itself and its body will be stable (even after switching pages), the click listener will remain valid.
$('#example1 tbody').on('click', 'td', function() {
// ... your code
});
Additional explanation on the jQuery website: https://learn.jquery.com/events/event-delegation/
With a nudge from #Johannes, I was able to at least google the right terminology for the delegated event handler
In combination of the posted links and the search, I was able to successfully fix/handle the issue.
The biggest change declaring a table, changing 'tr' to 'button', and using $(this).text() to get the cell information of the button.
Not sure if this is ideal, best practices, or a solid solution but its working and used until told otherwise.
var table = $('#example1').DataTable();
$('#example1 tbody').on('click', 'button', function () {
var asset_id = $( this ).text();
<!-- ajax call -->
});

How to pass parameters to a modal using thymeleaf?

I just starting in a project where we're using thymeleaf and I'm new to the technology.
It's a simple modal to confirm an object to be deleted. So they want me to add the name of the item we're deleting on the message instead of a generic message like: "Are you sure you want to delete?"
They want: "Are you you want to delete Item_Name?"
So I need to pass this name as parameter.
That's the code I have the display the modal:
<button id="btnDelete" value="delete" type="button" class="btn-link" data-toggle="modal" data-object-id="12345" data-object-name="NNN" th:attr="data-object-id=''+${assignment.assignmentId}+'', data-object-name='/nonInstructionalWorkload/deleteAssignment?asssignmentId='+${assignment.assignmentId}+'', data-target='#deleteAssignmentModal'">
And that's the code I have on the modal html:
<form role="form" th:action="#{/deleteAssignment}"
name="assignmentDeleteForm" id="assignmentDeleteForm" method="post">
<div class="modal-header">
<h4 class="modal-title" id="deleteWorkItemabel">Confirm Assignment Delete</h4>
</div>
<div class="modal-body">
<div class="form-group">
<p>Assignment will be deleted, are you sure you want to proceed?</p>
<input type="hidden" id="deleteId" name="deleteId" value="nnnn"/>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="btnDelConfirm" class="btn btn-primary">
Yes
</button>
<button type="button" id="btnDelCancel" class="btn btn-default" data-dismiss="modal">
No
</button>
</div>
</form>
At this point is where I need to add more information on the confirmation message about the assignment item being deleted.
Already tried some approached to get the parameters but didn't work so I'm looking for more option.
Thank you!
Thymeleaf is just template engine that takes your templeate and generate static html out of it. So passing dynamic values to your modal is a javascript work (unless you generate separate modal for each item, but this would be silly).
Using thymeleaf you have to generate a data- attribute containing desired item's name inside the button which opens modal, and that's all. You've already did such thing within th:attr:
th:attr="data-object-id=''+${assignment.assignmentId}+'', data-object-name='/nonInstructionalWorkload/deleteAssignment?asssignmentId='+${assignment.assignmentId}+'', data-target='#deleteAssignmentModal'"
The code above will generate attributes data-object-id,data-object-name and data-target inside the button. I assume that data-object-name is the one you want to use (however it looks more like an URL).
Now you can customize your modal's content using javascript. I can see, that you are using bootstrap as your frontend library, so you should take a look at this example, to have an idea how to accomplish that.
Javascript code below should work fine for you:
$('#deleteAssignmentModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var objectName = button.data('object-name') // Extract info from data-object-name attribute
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-body p').text('Do you want to delete ' + objectName + '?')
})
The sample project on GitHub you can clone and test it. Full video under the readme.
https://github.com/ibrahimkarayel/todoBoot/blob/master/src/main/resources/templates/home.html
<div class="modal modal-delete" th:id="modal-delete+${task.id }">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×
</button>
<h3 id="delModalLabel">Delete Confirmation</h3>
</div>
<div class="modal-body">
<p class="error-text"><strong>Are you sure you want to
delete this task ?</strong></p>
</div>
<div class="modal-footer">
<button class="btn " data-dismiss="modal" aria-hidden="true">
Cancel
</button>
<a th:href="#{/task/delete/{id}(id=${task.id})}">
<span class="btn btn-danger" value="delete">Delete</span></a>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!--end delete modal-->
<script>
$('#modal-delete').on('show.bs.modal', function (e) {
$(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
$('#modal-deleteHiddenId').val($(this).find('.btn-ok').attr('href'));
});
</script>

Display text from controller AngularJS

I have a datepicker and when the user enters an invalid date I want to display a proper message
$scope.setDate = function(startDate, endDate) {
$rootScope.startDate = $scope.startDateL;
$rootScope.endDate = $scope.endDateL;
if(($rootScope.startDate == undefined) || ($rootScope.endDate == undefined)){
console.log("choose a valid date");
$mdDialog.show({
cotnroller: DatePickerErrorController,
templateUrl : 'components/jags-date-picker-select/jags-date-picker-modal-valid-date.html',
parent : angular.element(document.body),
clickOutsideToClose:true
}).then(function(answer) {
console.log("Fff");
}, function() {
});
If the date that I want to set is undefined that means that the user has not entered one I want to display a modal with a proper text.
This is the controller for my modal
function DatePickerErrorController($scope, $rootScope){
$scope.text = function(){
return "Some text";
}
}
I want to do some checkings in my DatePickerErrorController. Something like if the startdate is undefined return some text.
This is the modal that should be displayed with a proper message.
<!-- Modal -->
<md-dialog aria-label="Date Picker">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">{{"Error message" | translate}}</h4>
</div>
<!-- /.modal-header -->
<div class="modal-body">
{{text}}
</div>
<!-- /.modal-body -->
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
</md-dialog>
<!-- /.modal -->
Now, the problem is that the modal shows up but it is not displaying "Some text". The modal is just blank. Have I done something wrong? This is not the correct way to display a text in html? Somebody with any ideas ?
Thanks in advance!