Updating certain Primefaces Diagram Element - javascript

I am trying since 2 days to solve a issue I got with my primefaces diagram implementation.
I want on "mouseover" the diagram elements, highlight other elements that are connected with that element.
I have it working, but ONLY if I update the whole diagram/form when I update the elements.
I have two problems with that approach.
First with the constant updates on mouseover all the binding on mouseenter and other stuff, gets reset so I have the event fire all the time although I just entered. Also 80% of the time I dont catch the mouseleave / hover leave event because of the constant calls.
Also I cant scroll the diagram anymore as the constant updates on mouseover would reset the scroll. ;-)
So I tried to only update the diagram elements I actually changed on mouseover, but I could not find a way that worked for me...
I tried just updateing the element via primefaces RequestContect.update
I used all variations on the Id like:
1-0201
diagram-1-0201
diagram:diagram-1-0201
I tried a javascript query from primefaces execute. I got a ui cant be resolved error on that one. Although the same query works on the xhtml. I also couldnt figure out that error. Although I dont think it would help, as the same code doesnt work when executed in the html file aswell.
I tried just saving the connections in a diagram element value and then accessing this value via hidden input on the elements. I got the ids for the connected elements in my javascript but I could not update the elements via javascript aswell. "inside" (leftover commented code) was the variable I had for the hidden inputs that were referenced on the Element variable that stored the connections)
I got both the list and the single connected ids in javascript but couldnt manage to update the elements.
I am not that experienced in javascript. I used it for the first time a few days ago.
So how do I update the style of certain elements in the primefaces diagram without reloading the hole diagram?
There must be a very easy way to do it or an easy way to fix my approaches I just cant see.
It is working if I update the whole diagram as I said, but I cant do that on mouseover for obvious reasons.
I am using primefaces 6.0 with a apache tomcat 8.5
Picture of the setup with ids: http://i.imgur.com/9yTEabE.png
Picture of the javascript log for the events: http://imgur.com/mCgf0BU
my xhtml file:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<p:panelGrid columns="2" styleClass="borderless">
<h:graphicImage name="images/logo.gif" />
<h:outputLabel styleClass="h1" value="Diagram Viewer" />
</p:panelGrid>
<f:metadata>
<f:viewAction action="#{dataManager.onLoad}" />
</f:metadata>
</h:head>
<h:body>
<h:form id="tabMenuForm">
<p:menubar styleClass=".ui-menu .ui-menuitem-link"
model="#{dataManager.menuModel}" />
</h:form>
<h:form id="diagramForm">
<p:dialog widgetVar="statusDialog" modal="true" draggable="false"
closable="false" resizable="false" showHeader="false">
<p:graphicImage value="#{resource['images/defaultLoader.gif']}" />
</p:dialog>
<p:tooltip />
<p:diagram id="diagram" value="#{dataManager.model}"
styleClass="borderless" style="#{dataManager.diagramStyle}" var="el">
<f:facet name="element" id="diagramElement" widgetVar="element">
<h:outputLabel>
<p:commandLink
actionListener="#{tooltipManager.onElementClickedTwo()}"
styleClass="commandRemover">
<f:param name="selected" value="#{el.id}" />
<div class="elID">
<h:outputText value="#{el.id}" />
</div>
<div class="elName">
<h:outputText value="#{el.name}" sytleCLass="elName" />
</div>
</p:commandLink>
</h:outputLabel>
<!-- <h:outputText value="#{el.role}" style="display: inline; align-items: right; margin-top:0em;"/> -->
</f:facet>
</p:diagram>
<p:remoteCommand name="elementMouseOver"
actionListener="#{dataManager.onElementMouseOver}" />
<p:remoteCommand name="elementMouseOut"
actionListener="#{dataManager.onElementMouseOut}" />
<h:inputHidden id="someId" value="#{dataManager.selectedId}" />
<script type='text/javascript'>
$('.ui-diagram-element').hover(function(ev) {
var id = $(this).attr('id');
console.log(ev);
var id = $(this).attr('id');
//var inputs = $(this).find('input');
//console.log('INSIDE!' + inputs);
//var input = inputs[0].val();
//var val = $(input).val();
//console.log('VAL: ' + val);
//console.log('INSIDE!' + input);
//var string = '#diagramForm\\:diagram-' + input;
//$(string).addClass('ui-diagram-element-predecessor');
//+ val[i]));
elementMouseOver([ {
name : 'elementId',
value : id
} ]);
//console.log(val);
}, function(ev) {
//***leave***//
var id = $(this).attr('id');
});
</script>
Important part of the Bean:
private DiagramNode selected;
private String selectedId = "x";
private List<String> selectedList = new ArrayList<String>();
public String getSelectedId() {
return selectedId;
}
public void setSelectedId(String selectedId) {
this.selectedId = selectedId;
}
public List<String> getSelectedList() {
return selectedList;
}
public void setSelectedList(ArrayList<String> selectedList) {
this.selectedList = selectedList;
}
public void onElementMouseOver() {
String input = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("elementId");
System.out.println("DataManager: Input: " + input);
String[] mouseoverIdSplit = input.split("-", 2);
if (mouseoverIdSplit.length < 2)
return;
System.out.println("DataManager: Mouseover:" + mouseoverIdSplit[1]);
selected = DataLoader.WPCPTaskRows.get(mouseoverIdSplit[1]);
selectedId = mouseoverIdSplit[1];
selectedList = selected.connections;
for (String id : selected.connections) {
System.out.println("Setting StyleClass for " + id);
String elementToUpdate = "diagramForm:diagram-" + id;
System.out.println(elementToUpdate);
RequestContext.getCurrentInstance().update(elementToUpdate);
RequestContext.getCurrentInstance()
.execute("$('#" + elementToUpdate + "').addClass(ui-diagram-element-predecessor);");
}
// RequestContext.getCurrentInstance().update("scriptBean");
// RequestContext.getCurrentInstance().update("someId");
RequestContext.getCurrentInstance().update("diagramForm");
RequestContext.getCurrentInstance().update("diagram");
}
public class DiagramElement implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String id;
private String role;
private String predecessor;
private List<String> predecessorList;
public DiagramElement() {
}
public DiagramElement(String name, String id, String role, String predecessor, List<String> predecessorList) {
this.name = name;
this.id = id;
this.role = role;
this.predecessor = predecessor;
this.predecessorList = predecessorList;
}
+getter and setter

After more then 10 hours of insanity I FINALLY got it working.
I connected the strings for the ID in javascript not correctly.
Also I had to add 3 \\ to the string, because 1 was swallowed as a escape and I needed 2 for a javascript function to find the element with a ":" inside it.
Here is how I did it in the end:
<h:inputHidden value="#{el.predecessorList}" />
$('.ui-diagram-element').hover(
function(ev) {
var id = $(this).attr('id');
console.log(ev);
var id = $(this).attr('id');
var inputs = $(this).find('input');
console.log(inputs);
var input = inputs[1];
//var val = $(input).val();
//console.log('VAL: ' + val);
var array = input.value;
console.log(array);
var parsedArray = array.replace("[", "").replace("]",
"").replace(/\s/g, "").split(',');
for ( var pos in parsedArray) {
var str1 = '#diagramForm\\\:diagram-';
var str2 = parsedArray[pos];
console.log(str2);
var con = str1.concat(str2);
console.log(con);
$(con).addClass('ui-diagram-element-predecessor');
}
},
function(ev) {
//***leave***//
var id = $(this).attr('id');
console.log(ev);
var id = $(this).attr('id');
var inputs = $(this).find('input');
console.log(inputs);
var input = inputs[1];
//var val = $(input).val();
//console.log('VAL: ' + val);
var array = input.value;
console.log(array);
var parsedArray = array.replace("[", "").replace("]",
"").replace(/\s/g, "").split(',');
for ( var pos in parsedArray) {
var str1 = '#diagramForm\\\:diagram-';
var str2 = parsedArray[pos];
console.log(str2);
var con = str1.concat(str2);
console.log(con);
$(con).removeClass('ui-diagram-element-predecessor');
}
});

Related

Edit->Find for WebView2 UI Component (WPF/C#/javascript)

I need to implement "Edit->Find" function for a WebView2 UI Component using WPF/C#/javascript... Below you will find two examples: One that is made for a TextBox UI Control called MainWindow1, and the other that is implemented for a WebView2 UI Control that is called MainWindows2. I'm giving both examples because I need to work the same way for each one. The TextBox example is working, but the WebView2 example is missing some javascript code to finish it and maybe requires some tweeting of the C# calls to WebView2.
First, I implemented a "Find Forward" button for a TextBox that I can click multiple times to find the next string matching the search pattern in the textbox. And Here's my XML and C# for it:
MainWindow1 GUI:
MainWindow1 XML:
<Window x:Class="WpfApp1.MainWindow1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Loaded="Window_Loaded"
Title="MainWindow1" Height="450" Width="800">
<DockPanel LastChildFill="True">
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top" Background="Aqua">
<TextBox Name="TboxFind" Width="80" Text="id"/>
<Button Name="FindForward" Content="FindForward"
Click="FindForward_Click"/>
</StackPanel>
<TextBox Name="textbox1" VerticalScrollBarVisibility="Auto"/>
</DockPanel>
</Window>
MainWindow1 C#:
using System.Text.RegularExpressions;
using System.Windows; using System.Windows.Controls;
namespace WpfApp1 {
public partial class MainWindow1 : Window {
public MainWindow1() {InitializeComponent();}
private void Window_Loaded(object sender, RoutedEventArgs e) {
string text1 = "";
for (int i = 0; i < 10000; i++) {
text1 = text1 + "id" + i.ToString() + "\n";}
textbox1.Text = text1;textbox1.Focus();textbox1.CaretIndex = 0;
}
private void TextBoxGotoLine(TextBox textbox1, int linenum) {
var target_cpos
= textbox1.GetCharacterIndexFromLineIndex(linenum);
var target_char_rect
= textbox1.GetRectFromCharacterIndex(target_cpos);
var first_char_rect = textbox1.GetRectFromCharacterIndex(0);
textbox1.ScrollToVerticalOffset(target_char_rect.Top
- first_char_rect.Top);
}
private void FindForward_Click(object sender, RoutedEventArgs e) {
string pattern = #"(?i)(" + Regex.Escape(TboxFind.Text) + #")";
string text1 = textbox1.Text.Substring(
textbox1.CaretIndex + textbox1.SelectionLength);
var match1 = Regex.Match(text1, pattern);
if (match1.Success) {
textbox1.Focus();
textbox1.Select(textbox1.CaretIndex
+ textbox1.SelectionLength
+ match1.Index, match1.Groups[0].Length);
} //if
} //function
}/*class*/ }/*namespace*/
The problem I'm having is that I also need this same feature for a WebView2 UI Control.
So I install the WebView2 UI Control:
WebView2 Install:
PM > Install-Package Microsoft.Web.WebView2
Add to XML: xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
using Microsoft.Web.WebView2.Core;
And here's my corresponding XML and C# demo code that should work the same as the first example I have given:
MainWindow2 GUI:
MainWindows2 XML:
<Window x:Class="WpfApp1.MainWindow2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wv2
="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Loaded="Window_Loaded"
Title="MainWindow2" Height="450" Width="800" >
<DockPanel LastChildFill="True">
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top" Background="Aqua">
<TextBox Name="SearchStr" Width="80" Text="id"/>
<Button Name="FindForward"
Content="FindForward" Click="FindForward_Click"/>
</StackPanel>
<wv2:WebView2 Name="webview2" CoreWebView2InitializationCompleted
="webview2_CoreWebView2InitializationCompleted" />
</DockPanel>
</Window>
MainWindow2 C#:
using System.Windows; using System.Threading;
using Microsoft.Web.WebView2.Core;
namespace WpfApp1 {
public partial class MainWindow2 : Window {
public MainWindow2() {InitializeComponent(); SearchStr.Focus(); }
private async void Window_Loaded(object sender, RoutedEventArgs e) {
await webview2.EnsureCoreWebView2Async();
}
private void webview2_CoreWebView2InitializationCompleted(
object sender, CoreWebView2InitializationCompletedEventArgs e)
{
string html = "";
for (int i = 0; i < 100; i++) {
string id = "id" + i.ToString();
html = html + "<b>" + id + "</b><br/>";
}
webview2.CoreWebView2.NavigateToString(html);
}
private async Tasks.Task<string> Find(string pattern) {
string js = "";
js = js + "var m1 = document.getElementById(""body"")";
js = js + "/*... ??? what goes here ??? */";
// Find and highlight one at a time, and scroll into view ...
// repeat find from beginning of html body when done ...
// See MainWindow1 example with TextBox for desired behavior here.
return await webview2.ExecuteScriptAsync(js);
}
private void async FindForward_Click(object s, RoutedEventArgs e) {
await Find(SearchStr.Text);
}
}/*class*/ }/*namespace*/
How to use WebBrowser UI Control to do a:
Menu->Edit->Find "SearchStr1"
When I click FindForward Button? I'm thinking it has something to do with executing Javascript on the DOM? each time the button is pressed?

Display the Selected Data With Jumbling

This is my C# code for Jumbling the data.
protected void Button1_Click1(object sender, EventArgs e)
{
ScrambleData("dsafdsfsd");
}
public static string ScrambleData(string data)
{
//string BaseAddress = "http://localhost/";
string BaseAddress = "http://abcd/"; //Calling by Computer Name.
string uri = "ScramblerService/Scrambler?value=" + data;
string CompleteRequestURL = BaseAddress + uri;
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(CompleteRequestURL);
//webrequest.Method = "GET";
webrequest.ContentType = "application/json";
string result;
using (WebResponse response = webrequest.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
return result;
}
}
}
This is my Java Script code for User selected Data.
<script type="text/javascript">
function disp()
{
var txtArea = document.getElementById('MainContent_TextArea1');
var start = txtArea.selectionStart;
var finish = txtArea.selectionEnd;
var sel = txtArea.value.substring(start, finish);
document.getElementById("MainContent_Textarea2").value = sel;
}
</script>
<div>
<asp:TextBox id="TextArea1" runat="server" TextMode="MultiLine" CssClass="form-control" Height="300px"></asp:TextBox>
<INPUT type="button" onclick= "disp()" visible="true" value="Show" class="btn btn-primary"/>
<input id="Textarea2" runat="server" type="text"/>
</div>
Here I am trying to display the user selected data. While displaying the user selected data I need to jumble the words and has to display in Text area2. But I need to call this action through "Show" button Only.
Any Help Please..???
Any Suggestions Please...???
You are referencing an id of "MainContent_Textarea2" but you don't have any element with that ID. You do, however, have one called "Textarea2", have you tried using that?
document.getElementById("Textarea2").value = sel;

How to pass value from javascript to label in asp.net?

I need to pass a javascript value to label in asp.net. The javascript function was inside JScript1.js. I pass the value to a hidden field. I already added the script to the source of the content page as below, but doesn't work whenever I called the function value to the vb.net code behind.
<script src="JScript1.js" type="text/javascript"></script>
Here's the javascript function inside a JScript1.js
function dateTimeToday()
{
var month=new Array();
month[0]="1";
month[1]="2";
month[2]="3";
month[3]="4";
month[4]="5";
month[5]="6";
month[6]="7";
month[7]="8";
month[8]="9";
month[9]="10";
month[10]="11";
month[11]="12";
var d = new Date();
var mt=month[d.getMonth()];
var h=d.getHours();
var m=d.getMinutes();
var s=d.getSeconds();
mt=checkMonth(mt);
m=checkTime(m);
s=checkTime(s);
var x = document.getElementById("HiddenField1");
x.innerHTML=d.getFullYear()+"-"+mt+"-"+d.getDate()+" " +h+":"+m+":"+s;;
t=setTimeout(function(){myFunction()},500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
function checkMonth(j)
{
if (j<10)
{
j="0" + j;
}
return j;
}
Below is my code of calling the javascript value.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
lbl.Text = HiddenField1.Value
End If
End Sub
Am I missing something on my code?
Please help.
Thanks in advance.
You need to set the value of the input field, not the innerHtml:
var x = document.getElementById("HiddenField1");
x.value =d.getFullYear()+"-"+mt+"-"+d.getDate()+" " +h+":"+m+":"+s;
And consider that the ID of asp.net control can change when the page is rendered, you could use:
var x = document.getElementById('<%= HiddenField1.ClientId %>');
x.value =d.getFullYear()+"-"+mt+"-"+d.getDate()+" " +h+":"+m+":"+s;
I hope you want to set value in Hiddenfield in javascript..You can do..
document.getElementById("HiddenField1").value=d.getFullYear()+"-"+mt+"-"+d.getDate()+" " +h+":"+m+":"+s;
In code behind..
lbl.Text = HiddenField1.Value;
Hidden input markup..
<input id="HiddenField1" type="hidden" runat="server" clientidmode="Static" value=""/>

mvc 4 - javascript button stop working after enter text

I read a lot of posts that looked similar to this issue, but none of them helped me. I have this button that adds text to a textarea. However, if i enter text manually in the textarea, the button stops do work. What am i doing wrong?
Model:
public class WhateverModels
{
public string TheText { get; set; }
}
Controller:
public class WhateverController : Controller {
public ActionResult Index()
{
SelectList tokens = new SelectList(new string[] { "A", "B", "C" });
this.ViewBag.tokens = tokens;
WhateverModels w = new WhateverModels();
return View(w);
}
}
View:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%: Html.TextAreaFor(x => x.TheText) %>
<br />
<%: Html.DropDownList("tokens", string.Empty)%>
<br />
<button type="button" id="AddButton" onclick="addToken()">test</button>
<script>
function addToken() {
var combo = document.getElementById("tokens");
document.getElementById("TheText").textContent =
document.getElementById("TheText").textContent +
"[" + combo.options[combo.selectedIndex].value + "]";
}
</script>
</asp:Content>
Step by step:
1) Open the page
2) Click test button (note that the text is added to the textarea)
3) Enter the textarea and type something
4) Click test button (now it does not work)
(using firefox)
Thanks for your attention
The textContent attribute is not well supported in some browsers. It is better to use textArea.value for setting text:
function addToken() {
var combo = document.getElementById("tokens");
document.getElementById("TheText").value +=
"[" + combo.options[combo.selectedIndex].value + "]";
}
For some reason on FF and Chrome setting textContent does not update the UI.

how to do postback Javascript, jquery

<asp:Button ID="btn" OnClientClick="if(confirm_delete()){
/* post back*/
}else{
return false;
};" OnClick="btnDelete_Click" runat="server" Text="delete"/>
Hi I have this code but I cant do postback for it, im not sure how to?
is it:
<script type="text/javascript">
function CallServer() {
__doPostBack('not sure what goes here','or here');
}
</script>
Then:
<asp:Button ID="btn" OnClientClick="if(confirm_delete()){
/CallServer()/
}else{
return false;
};" OnClick="btnDelete_Click" runat="server" Text="delete"/>
My other script:
<script type="text/javascript">
function confirm_delete()
{
if (confirm("Are you sure you want to delete this comment?")==true)
return true;
else
return false;
}
</script>
EDIT:
On the server side i dynamically add a div to my page with content from my database for each content there is a new div will be added, each div is then refrenced with idWallPosting (so i can call my delete function)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Odbc;
using System.IO;
public partial class UserProfileWall : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//btn.Visible = false;
string theUserId = Session["UserID"].ToString();
PopulateWallPosts(theUserId);
}
private void PopulateWallPosts(string userId)
{
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("SELECT idWallPosting, wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN User u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE wp.UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
{
//("SELECT wp.WallPostings, p.PicturePath FROM WallPosting wp LEFT JOIN [User] u ON u.UserID = wp.UserID LEFT JOIN Pictures p ON p.UserID = u.UserID WHERE UserID=" + userId + " ORDER BY idWallPosting DESC", cn))
using (OdbcDataReader reader = cmd.ExecuteReader())
{
test1.Controls.Clear();
while (reader.Read())
{
System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
div.Attributes["class"] = "test";
div.ID = String.Format("{0}", reader.GetString(0));
// this line is responsible, problem here and my sqlsntax, im trying to set the SELECT idWallPosting for the div ID
Image img = new Image();
img.ImageUrl = String.Format("{0}", reader.GetString(2));
img.AlternateText = "Test image";
div.Controls.Add(img);
div.Controls.Add(ParseControl(String.Format("&nbsp&nbsp " + "{0}", reader.GetString(1))));
div.Attributes.Add("onclick", "return confirm_delete();");
div.Style["clear"] = "both";
test1.Controls.Add(div);
}
}
}
}
}
//protected void btnDelete_Click(object sender, EventArgs e)
//{
// string id = "ctl00_ContentPlaceHolder1_ContentPlaceHolder2_26";
// string[] idFragments = id.Split('_');
// id = idFragments[idFragments.Length - 1];
// //serverside code if confirm was pressed.
// using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
// {
// cn.Open();
// using (OdbcCommand cmd = new OdbcCommand("DELETE FROM WallPosting WHERE idWallPosting = " + id + ")", cn))
// {
// cmd.ExecuteNonQuery();
// }
// }
// //PopulateWallPosts();
//}
protected void Button1_Click(object sender, EventArgs e)
{
string theUserId = Session["UserID"].ToString();
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings) VALUES (" + theUserId + ", '" + TextBox1.Text + "')", cn))
{
cmd.ExecuteNonQuery();
}
}
PopulateWallPosts(theUserId);
}
protected void btn_Click(object sender, EventArgs e)
{
string id = "ctl00_ContentPlaceHolder1_ContentPlaceHolder2_26";
string[] idFragments = id.Split('_');
id = idFragments[idFragments.Length - 1];
//serverside code if confirm was pressed.
using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;"))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand("DELETE FROM WallPosting WHERE idWallPosting = " + id + ")", cn))
{
cmd.ExecuteNonQuery();
}
}
//PopulateWallPosts();
}
}
On my asp.net html side i have:
<script type="text/javascript">
function confirm_delete()
{
if (confirm("Are you sure you want to delete this comment?")==true)
return true;
else
return false;
}
</script>
<p>
<asp:Button ID="btn" OnClientClick="return confirm_delete();" runat="server"
CssClass="Btn" Text="delete" onclick="btn_Click"/>
<asp:TextBox ID="TextBox1" name="TextBox1" runat="server" Rows="3"
Height="47px" Width="638px"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Post Message" Width="98px"
onclick="Button1_Click" />
</p>
<p>
</p>
<style type="text/css">
img {border-width:0px; width:100px; height:100px;}
</style>
<div id="test1" runat="server" />
</div>
</asp:Content>
If you notice in my server side code I added this line:
div.Attributes.Add("onclick", "return confirm_delete();")
This works any time I click on my div the confirm_delete is called.
What I was trying to do with my asp.net button was when the div was clicked I could then call the onclick btnDelete_click.
OnClientClick="return confirm_delete();"
That's it...
Edit: __doPostBack works also...
OnClientClick="if(confirm('delete?'))__doPostBack('btn',''); else return false;"
If you really are wanting to manually call __doPostBack(), the first parameter is the .NET generated name for the control. This can be gotten on the server side using Control.ClientID. The second parameter is any extra data that should be passed along in the request. Most of the time I see this field is an empty string.
__doPostBack('ctl100$controlName$id','');
The controlName is the .NET class name of the control I believe, id is the ID you gave the control. To be sure, view the source of the page after it has been rendered in the browser and search for calls to __doPostBack and see how they are formatted.
By a postback in this case do you want to just refresh the page? If so then it would just be:
location.reload();
in your case:
<script type="text/javascript">
function CallServer()
{
location.reload();
}
</script>
Demo (A button click prompts the user to confirm - if they choose Yes, a post back occurs)
See demo here!
One method, not the best for sure:
Add a button into an update panel and set it invisble.
Then call click() method of the button.
Somthing like this:
document.getElementById('button').click();

Categories

Resources