Document.ready() failing on popup - c#

I am using ASP.Net and jQuery/jQuery UI and I am trying to use the datepicker control. It works fine on every page, except when I have to use the popup (to add new data into the database and then i refresh the current page to reflect the new data being entered). It seems that document.ready() is failing when I use the popup. I can invoke the datepicker control manually with adding a click event to fire off the showcalendar function, however I want to try and make it work. Does anyone have any ideas of why a popup would fail document.ready() ?
Thanks!
Code in UserInterfaces.js Script File:
$(document).ready(function(){
$(".calendarTrigger").datepicker({showOn:'focus', showAnim: 'fadeIn', changeMonth: true, showOn:'both', buttonImage: '/images/calendar.gif', buttonImageOnly: true, changeYear: true, yearRange: '1950:2010'});
});
Code Calling Popup Functionality:
<a href="#" onclick='javascript:openWindow("/modules/prh/AI.aspx","PH","480","650","","");'
Code For Modal Popup That we use:
function openWindow(url,name,height,width,left,top)
{
if(!width) {width = 625};
if(!height){height = 625};
if(!left) {left = 60};
if(!top){top = 60};
if (!name) {name='mk'};
name = name.replace(" ","");
if ((window.showModalDialog) && (navigator.appName!="Microsoft Internet Explorer"))
{
grayOut(true);
newWindow = window.showModalDialog(url,"name","dialogWidth: " + width + "px;dialogHeight: " + height + "px;resizable: 1;status: 0;scrollbars: 1;dialogLeft: " + left +"px;dialogTop: " + top + "px");
if (newWindow)
newWindow.focus();
grayOut(false);
}
else
{
newWindow = window.open(url,name,'width=' + width + ',height='+ height +
',resizable=1,status=0,scrollbars=1,left=' + left +',top=' + top);
if (newWindow)
newWindow.focus();
else
window.Name.focus();
}
}
function grayOut(vis, options) {
// Pass true to gray out screen, false to ungray
// options are optional. This is a JSON object with the following (optional) properties
// opacity:0-100 // Lower number = less grayout higher = more of a blackout
// zindex: # // HTML elements with a higher zindex appear on top of the gray out
// bgcolor: (#xxxxxx) // Standard RGB Hex color code
// grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
// Because options is JSON opacity/zindex/bgcolor are all optional and can appear
// in any order. Pass only the properties you need to set.
var options = options || {};
var zindex = options.zindex || 50;
var opacity = options.opacity || 70;
var opaque = (opacity / 100);
var bgcolor = options.bgcolor || '#000000';
var dark=document.getElementById('darkenScreenObject');
var tbody = document.getElementsByTagName("body")[0];
if (!dark)
{
// The dark layer doesn't exist, it's never been created. So we'll
// create it here and apply some basic styles.
// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
var tnode = document.createElement('div'); // Create the layer.
tnode.style.position='absolute'; // Position absolutely
tnode.style.top='0px'; // In the top
tnode.style.left='0px'; // Left corner of the page
tnode.style.overflow='hidden'; // Try to avoid making scroll bars
tnode.style.display='none'; // Start out Hidden
tnode.id='darkenScreenObject'; // Name it so we can find it later
tbody.appendChild(tnode); // Add it to the web page
dark=document.getElementById('darkenScreenObject'); // Get the object.
}
if (vis)
{
var pageWidth="100%";
var pageHeight=getPageHeightWithScroll();
if (window.innerHeight>pageHeight)
pageHeight = window.innerHeight;
pageHeight = pageHeight + "px";
//set the shader to cover the entire page and make it visible.
dark.style.opacity=opaque;
dark.style.MozOpacity=opaque;
dark.style.filter='alpha(opacity='+opacity+')';
dark.style.zIndex=zindex;
dark.style.backgroundColor=bgcolor;
dark.style.width= pageWidth;
dark.style.height= pageHeight;
dark.style.display='block';
}
else
{
dark.style.display='none';
}
}

What is the markup for your popup and do you have any other javascript that could possibly cause an error before datepicker fires inside the popup?

Related

WinUI3: Get the WebView2 HTML height

I'm currently using a WebView2 in my WinUI3 application to display some HTML which is sent from our server.
The HTML itself doesn't contains a body / html tags and is displayed through NavigateToString:
await web.EnsureCoreWebView2Async();
web.NavigationCompleted += async (sender, args) => await sender.ResizeToContent(); // more about this later
web.NavigateToString(someText);
When I display this HTML in my WebView, the WebView's height is always set at 0 by default, and I want my WebView to autosize to its content (I cannot set a fixed sized for its container and stretch the webview to it).
I tried executing scripts found there to evaluate the HTML's size:
How to get height of entire document with JavaScript? :
public static async Task ResizeToContent(this WebView2 webView)
{
var script = "";
var heightString = await webView.ExecuteScriptAsync(script);
int height = 0;
if (int.TryParse(heightString, out height))
{
webView.Height = height;
}
}
Here are 2 differents scripts I tried:
eval(document.documentElement.scrollHeight.toString());
and
;(function() {
var pageHeight = 0;
function findHighestNode(nodesList) {
for (var i = nodesList.length - 1; i >= 0; i--) {
if (nodesList[i].scrollHeight && nodesList[i].clientHeight) {
var elHeight = Math.max(nodesList[i].scrollHeight, nodesList[i].clientHeight);
pageHeight = Math.max(elHeight, pageHeight);
}
if (nodesList[i].childNodes.length) findHighestNode(nodesList[i].childNodes);
}
}
findHighestNode(document.documentElement.childNodes);
return pageHeight;
})();
But in both cases, no mater the HTML provided, it always returns 1040 even with a simple HTML such as <p>test</p>
When I set a fixed height for my WebView, let's say of 60, this p is displayed correctly without scrollbar (while my script would return a height of 1040) BUT when I do some complex HTML intended to be bigger than those 60px, the webview displays a vertical scrollbar.
So all in one, it seems the WebView somehow knows that 1040 is not the real height (otherwise I'd have a scrollbar all the time).
Note that I've also tried to surround my text with <html><body>{myText}</body></html> with the same result.
How can I get the real actual content's height?
Thanks.
After trying other solutions, here is what I came up with which seems to work:
In my ViewModel:
Text = $"<div id='container'>{_source.Text}</div>";
And in my extension method to get the height:
public static async Task ResizeToContent(this WebView2 webView)
{
var script = "eval(document.getElementById('container').getBoundingClientRect().height.toString());";
var heightString = await webView.ExecuteScriptAsync(script);
if (int.TryParse(heightString, out int height))
{
webView.Height = height + 30;
}
}
I had to add the +30 because otherwise the scrollbar was displayed and the webview's content slightly truncated.
Is there any cleaner and less hacky way to do this?

C# WPF dynamic names for input

So I'm trying to add dynamically inputs and retreive date from them and only do an action when a user presses enter in the input. So, what I'm currently doing is appending the inputs to a stacklayout. which works fine. Also the naming works. I use the following function;
private void GenerateGTKInputs()
{
// Based on the settings for the tour
// we generate the correct inputs in the stacklayout given in the XAML
// First: clear all the children
stackpanel_gtk.Children.Clear();
if (inp_team_number.Text != "")
{
// get the data for the part and the class etc...
var data_gtk = tour_settings[(Convert.ToInt32(inp_team_number.Text.Substring(0, 1)) - 1)].tour_data[inp_tour_part.SelectedIndex].gtks;
// Now: Make the layout
foreach (var item in data_gtk)
{
// Stack panel (main 'div')
StackPanel main_stack_panel = new StackPanel()
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Left
};
// Text blok with the name of the GTK
TextBlock gtk_name = new TextBlock()
{
FontWeight = FontWeights.Bold,
Text = "GTK " + item.gtk
};
// Input field
Xceed.Wpf.Toolkit.MaskedTextBox input = new Xceed.Wpf.Toolkit.MaskedTextBox()
{
Margin = new Thickness(15, 0, 0, 0),
Width = 40,
Height = Double.NaN, // Automatic height
TextAlignment = TextAlignment.Center,
Mask = "00:00",
Name = "gtk_" + item.gtk
};
// Add to the main stack panel
main_stack_panel.Children.Add(gtk_name);
main_stack_panel.Children.Add(input);
// Append to the main main frame
stackpanel_gtk.Children.Add(main_stack_panel);
}
}
}
Now as you can see, I'm giving them a name, but I have no clue what so ever on how to "bind" an trigger event (KeyDown) with a check on enter button press with dynamic names. Could anyone help me out here?
You "bind" a trigger event by adding to the appropriate event of the control - in this case you need to create a method like :
private void OnKeyDown(object sender, System.Windows.Input.KeyEventArgs keyEventArgs)
{
// Get reference to the input control that fired the event
Xceed.Wpf.Toolkit.MaskedTextBox input = (Xceed.Wpf.Toolkit.MaskedTextBox)sender;
// input.Name can now be used
}
and add this to the KeyDown event :
input.KeyDown += OnKeyDown;
You can chain as many event handlers as you want by adding further handlers in this fashion.
This can be done at any time after you create the control. To "unbind" the event you "subtract" it from the event :
input.KeyDown -= OnKeyDown;

Placing multiple instances of same control on form

I am making an application in winforms which shows a blueprint in a picturebox, and I need to place parts on it programmatically. These parts needs to be clickable (thus they should be a user control), and then fire the corresponding click event (clicking on a part should display information unique to that part). I could say that I want to place custom buttons on my picture. Now, of course, I need only one click event, and change the displayed information according to selection, though I don't know how to "link" this event to each created button.
I have a list of parts right next to the picturebox, and selecting a part should make the associated control to appear on the form (and deselecting it should remove it, or at least make it hidden). At first, I thought I will create one control during design, and make it appear/disappear and relocate it with each selection. The problem is, that the user should be able to select multiple parts, and the program should show all selected parts on the blueprint.
As each blueprint is different, the number of parts cannot be defined in advance. Is it possible, to create multiple instances of the same control on the run? Or is there a workaround?
If you use controls for your picture elements( you do not determine anything from coordinates of mouse click) and each picture element is associated with only one menu control, then I can propose you to use the Tag property to associate the corresponding menu controls:
public Form1()
{
InitializeComponent();
this.CreatePictureRelatedControls();
}
private void CreatePictureRelatedControls()
{
Int32 xPictureControls = 50,
yPictureControls = 50,
xAssociatedControls = 200,
yAssociatedControls = 50,
yMargin = 10;
Int32 controlWidth = 125,
controlHeight = 20;
Int32 controlCount = 3;
// ---------Associated controls-----------------
var associatedControls = new Button[controlCount];
// Loop - creating associated controls
for (int i = 0; i < associatedControls.Length; i++)
{
var associatedButton = new Button()
{
Left = xAssociatedControls,
Top = yAssociatedControls + (i * (controlWidth + yMargin)),
Width = controlWidth,
Height = controlHeight,
Text = String.Format("associated control {0}", i),
Visible = false
};
// Event handler for associated button
associatedButton.Click += (sender, eventArgs) =>
{
MessageBox.Show(((Control)sender).Text, "Associated control clicked");
};
associatedControls[i] = associatedButton;
}
// ----------------- Picture controls ---------------
var pictureControls = new Button[controlCount];
// Loop - creating picture controls
for (int i = 0; i < pictureControls.Length; i++)
{
var pictureButton = new Button()
{
Left = xPictureControls,
Top = yPictureControls + (i * (controlWidth + yMargin)),
Width = controlWidth,
Height = controlHeight,
Text = String.Format("picture part button {0}", i),
// Use of tag property to associate the controls
Tag = associatedControls[i],
Visible = true
};
// Event hadler for picture button
pictureButton.Click += (sender, eventArgs) =>
{
Control senderControl = (Control)sender;
Control associatedControl = (Control)senderControl.Tag;
associatedControl.Visible = !associatedControl.Visible;
};
pictureControls[i] = pictureButton;
}
this.Controls.AddRange(associatedControls);
this.Controls.AddRange(pictureControls);
}
P.S. If you need to associate multiple controls then you can just set Tag property to some collection:
button.Tag = new Control[] {associated[1], associated[3]};

load JQuery with MasterPage C#

I using this code below, and its operation is normal but when using with MasterPage its behavior has serious problems thecode not function.
/// script /////
$(".cssopen").click(function (e) {
//Cancel the link behavior
e.preventDefault();
//Get the A tag
//var id = $(this).attr('href');
//alterado
var id = '.window';
var body = $("html");
//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
//Set height and width to mask to fill up the whole screen
$('#mask').css({ 'width': maskWidth, 'height': maskHeight });
//transition effect
$('#mask').fadeIn(1000);
$('#mask').fadeTo("slow", 0.8);
//Get the window height and width
var winH = $(window).height();
var winW = $(window).width();
//Set the popup window to center
$(id).css('top', winH / 2 - $(id).height() / 2);
$(id).css('left', winW / 2 - $(id).width() / 2);
//inserido
href = $(this).attr("href");
$('.window').load(href);
//transition effect
$(id).fadeIn(2000);
//$(id).show();
$(id).show().position({ my: "center", at: "center", of: "html" });
});
//if close button is clicked
$('.window .close').click(function (e) {
//Cancel the link behavior
e.preventDefault();
$('#mask, .window').hide();
});
//if mask is clicked
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
});
/////////////// code .aspx //////////////////
<div>
<asp:ImageButton ID="imgBtCmd" runat="server" ImageUrl="~/Image/edit.png" href="frmIndexII.aspx" CssClass="cssopen"/>
</div>
I am not sure you have posted all the info required but i'm making an educated guess that you are grabbing controls by ID using jQuery and this has broken since introducing a master page. This is because the master page will change the client side id of the rendered HTML element.
If you are on .net4 and above you can use
<asp:SomeControl ClientIdMode="static">
And the controls will retain their Id client side. Alternatively you can add a class to your controls and jQuery them by class rather than ID.

styling div with javascript

I am trying to style a div which has an asp.net gridview within it.
I am using javascript code.
The div is a popup on asp.net buttonclick event.
I have the code below :
function ViewPopup() {
document.getElementById('PopupDiv').style.visibility = 'visible';
document.getElementById('PopupDiv').style.display = '';
var screenHeight = document.documentElement.clientHeight;
var elementHeight = document.getElementById('PopupDiv').clientHeight;
if (screenHeight > elementHeight) {
document.getElementById('PopupDiv').style.top = ((screenHeight - elementHeight) / 2) + 50 +'px';
}
else {
document.getElementById('PopupDiv').style.top = '10px';
document.getElementById('PopupDiv').style.bottom = '20px';
document.getElementById('PopupDiv').style.overflow = 'scroll';
}
var scrWidth = document.documentElement.clientWidth;
var elWidth = document.getElementById('PopupDiv').clientWidth;
document.getElementById('PopupDiv').style.left = ((scrWidth - elWidth) / 2) - 20 + 'px';
document.getElementById('MaskedDiv').style.display = '';
document.getElementById('MaskedDiv').style.visibility = 'visible';
}
The problem is that .. when the screenheight < elementheight , the control goes to the else statement and a popup
is displayed with scrollbar. Imagine the dimensions of the popup are x and y.
Next time when there is a button click , if screenheight > elementheight, the control goes to the if statement,
but the popup dimensions are again x and y. That is the dimensions are carried from the earlier button click event.
Is there any way I can make sure that the popup fits the gridview perfectly ?
Have you tried putting breakpoints on the var, var and if lines? Then slowly stepping through the code? I'd be curious if "slowing" down the JavaScript allows the correct elementheight and screenheight to be obtained. It's not much of an answer, but I had a similar situation where I had to slow down the code by putting a timer on it so it could get the right dimensions of my element, then continue on to my if statement after the fact. I'd show the code, but that is with a former employer...
I hope in some way this helps.

Categories

Resources