I'm trying to simulate a button click in my program in order to get the response from the server. The problem is that the web page "onclick" activate a script in that page
The html look like this:
<script language=javascript>
function frmsubmit(id)
{
document.all("HistoryData1_hiddenID").value=id;
document.all("Form1").submit();
}
</script>
<input type="button" id="btnGo" value="Go" Class="RegularButton" onclick="frmsubmit('0')" >
I used this code that i have seen:
WebBrowser wb = new WebBrowser();
wb.Navigate(url);
while (wb.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
wb.Document.GetElementById("btnGo").InvokeMember("click");
Nothing happens. In the real web page I get an html with data that I need. Any ideas?
you can use jquery like
$("#btnGo").click();
in your .cs you will use it like
StringBuilder sb = new StringBuilder();
sb.AppendLine("$(document).ready(function() {");
sb.AppendLine("$('#btnGo').click();");
sb.AppendLine(" });");
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", sb.ToString(), true);
thats it, of course you have to add jquery libraries to html page
Try calling doPostBack
__doPostBack("btnGo', '<event argument here>');
http://wiki.asp.net/page.aspx/1082/dopostback-function/
Use jQuery trigger() function (or triggerHandler, dependingo on your purpose).
I.e.
$('#<%=btnGo.ClientID%>').trigger('click');
Related
I want to implement a timer in asp.net web in which, after a time period, the text of a button is changed. I created the button dynamically in gridview and tried this code:
protected void Timer2_Tick(object sender, EventArgs e)
{
Label2.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString();
for(int i = 0; i< rowcount; i++)
{
Button button = new Button();
if (button.Text == "requested")
{
button.Text = "available";
}
}
}
But it doesn't work. How can I solve this problem?
This requires client code (JavaScript) that executes on the browser after the page is loaded. ASP.NET generates the page, sends it to the browser, and then the server is done with it until it gets another request. Even if you create a timer in your code-behind, that code-behind is a class that goes out of scope and disappears once the server is done processing the request.
In its simplest form, it would look something like this:
<script>
window.setTimeout(function()
{
//do something
}, 10000); //interval in milliseconds - this is 10 seconds.
<script>
In order to be able to change text, you'll need to make sure that your control has an ID that you can find using JavaScript. Usually whatever ID you use for a server control, ASP.NET is going to modify it somewhat. I'm oversimplifying this, but generally you can do this:
<asp:Label ID="myLabelId" ClientIDMode="Static" Text="The label text"></asp:Label>
or
<div runat="Server" ID="MyLabelId" ClientIDMode="Static">The label text</div>
ClientIdMode="Static" means that when the control is rendered to the page it won't modify the ID.
Then your script might look like this:
<script>
window.setTimeout(function()
{
var label = document.getElementById("MyLabelId");
label.textContent = "The new value";
}, 10000);
<script>
Or instead of using ClientIDMode="Static" you could try this in your script:
var label = document.getElementById("<%= MyLabelId.ClientID %>");
.ClientID is whatever ID the page assigns to the control. This tells it that whatever ID it assigns to that control, to write it directly into your script.
How to open a radwindow on the click event of a Imagebutton within a user control?
Moreover i have used the same code in aspx page and it works fine.
car.ascx
code behind car.ascx.cs
protected void btnCarLogo_Click(object sender, ImageClickEventArgs e)
{
carurl="https://www.google.co.in/"
ScriptManager.RegisterStartupScript(this, this.GetType(), "popCarWindow", "window.radopen('" + carurl + "', 'CarDetails');", true);
}
It has VisibleOnPageLoad property. If you set it to true, window will be visible after postback.
Examples:
Show window
myRadWindow.VisibleOnPageLoad = true;
Hide window
myRadWindow.VisibleOnPageLoad = false;
Take a look here: http://www.telerik.com/community/forums/aspnet-ajax/window/opening-radwindow-from-the-server.aspx and see that the parameters are Page and not this (i.e. UserCOntrol).
Here is on working with JS functio nnames in user controls: http://www.telerik.com/support/kb/aspnet-ajax/general/using-dynamic-unique-names-for-javascript-functions.aspx
And, if you are going to have more than one manager on the page: http://www.telerik.com/help/aspnet-ajax/radwindow-troubleshooting-wrong-window-opened.html.
That way probably you get errors stating that the window is null
Try it like this:
Code behind:
string script = "<script language='javascript' type='text/javascript'>Sys.Application.add_load(ShowWindow);</script>";
ClientScript.RegisterStartupScript(this.GetType(), "showWindow", script);
Then on your aspx:
<script type="text/javascript">
function ShowWindow()
{
var oWnd = window.radopen('https://www.google.co.in/', 'window1');
}
</script>
I have a Image Button declared as,
<div>
<asp:ImageButton ID="btnDoWork" runat="server" ImageUrl="/_LAYOUTS/1033/IMAGES/row.png" ValidationGroup="Page" />
</div>
<div>
<asp:RequiredFieldValidator runat="server" ID="reqName" ControlToValidate="txtEmail" ValidationGroup="Page" ErrorMessage="enter a email" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ValidationExpression="^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$" ControlToValidate="txtEmail" ValidationGroup="Page" ErrorMessage="enter a email" />
</div>
within a update panel,
now in code behind I am doing something like this,
btnDoWork = (ImageButton)this.control.FindControl("btnDoWork"); //this code is in childcontrols method
btnDoWork.Click += new ImageClickEventHandler(btnDoWork_Click);
then
protected void btnDoWork_Click(object sender, ImageClickEventArgs e)
{
//Process a bit of code and at end,
this.Page.Unload += new EventHandler(Page_Unload_MessageBox);
and then in button click event,
public static void Page_Unload_Page_Unload_MessageBox(object sender, EventArgs e)
{
System.Globalization.CultureInfo _culture = Thread.CurrentThread.CurrentUICulture;
StringBuilder sb = new StringBuilder();
sb.Append("<script language=\"javascript\">");
sb.Append("$('body').append(\"<div id='M'><span id='text'>" +
SPUtility.GetLocalizedString("$Resources:abc", "def", (uint)_culture.LCID) +
"</span><br/><div id='BB' onclick='return BB();'><a href='' onclick='return BB();'>" +
SPUtility.GetLocalizedString("$Resources:OK", "def", (uint)_culture.LCID) +
"</a></div></div>\");");
sb.Append("function BB() { $('#M').remove(); $('#E').remove(); return false; }");
sb.Append("function dM(){ var browser = navigator.appName; if (browser == 'Netscape') { $('#M').css({ 'top': '5%' }, 500); } }");
sb.Append("</script>");
// Write the JavaScript to the end of the response stream.
HttpContext.Current.Response.Write(sb.ToString());
Now if I put email address I get error while when it tries to Response.Write I think, I wonder what alternative is there, e.g. can I use triggers in update panel or any other event or something..
here's the error I am getting now,
Note: I changed all variable names so don't get confused if something doesn't match
The message is very clear, you can not add this command HttpContext.Current.Response.Write on update panel, and that because can not know how to handle it, because the update panel is return a struct that is used by the javascript to redraw some part of the page.
The solution is to add a literal control inside the UpdatePanel, in the place you wish to add the extra html code, and write that control the render as:
txtLiteralID.Text = sb.ToString();
How ever, here you have a diferent situation than the normal, you won to render and run a script.
The main problem is how to trigger the script to run. The only way is to use the UpdatePanel handler that is this standard code:
<script type="text/javascript">
// if you use jQuery, you can load them when dom is read.
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
});
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
// after update occur on UpdatePanel run the code.
UnloadMsgBox();
}
</script>
Now on the EndRequest you need to call your script, where it may all read exist in your code as:
function UnloadMsgBox()
{
// render your code of the javascript.
$('body').append(\"<div id='M'><span id='text'></span><br/><div id='BB' onclick='return BB();'><a href='' onclick='return BB();'></a></div></div>\");
function BB() { $('#M').remove(); $('#E').remove(); return false; }"
function dM(){ var browser = navigator.appName; if (browser == 'Netscape') { $('#M').css({ 'top': '5%' }, 500); } }"
}
and not need to render it on UpdatePanel.
To summarize:
On the update panel you can not use the Response.Write to render something but a literal control, that renders inside him.
On the update panel you can not render javascript code and expect to run, to run a javascript code you need to use the EndRequest handler that comes with the UpdatePanel.
MS Ajax calls perform full page rendering, calculate the diff from the original, send the diff to the client, and magically merge the diff in the browser.
If you just send javascript as response, it's something the framework does not expect and it throws the message.
See a previous answer on how to invoke javascript from an UpdatePanel.
I write script like this in my .cs file :
StringBuilder script = new StringBuilder();
script.Append("<script type=\"text/javascript\"> function submitform(){");
script.Append(" document.forms['" + ((HtmlGenericControl)frm).Attributes["id"] + "'].submit();} </");
script.Append("script>");
How can i call this function in the OnClientClick of my link button ?
LinkButton hl_process = new LinkButton();
hl_process.OnClientClick = ""
Edit1:
protected Control CreateCommForm()
{
HtmlGenericControl frm = new HtmlGenericControl("form");
frm.Attributes.Add("id", "sal");
frm.Attributes.Add("method", "post");
frm.Attributes.Add("action", "https://------");
/////////////////////////////////////////
HtmlGenericControl hdn_sal_a = new HtmlGenericControl("input");
hdn_sal_a.Attributes.Add("id", "hdn_sal_a");
hdn_sal_a.Attributes.Add("name", "hdn_sal_a");
hdn_sal_a.Attributes.Add("type", "hidden");
hdn_sal_a.Attributes.Add("value", Session["emp_num"].ToString());
/////////////////////////////////////////
HtmlGenericControl hdn_sal_b = new HtmlGenericControl("input");
hdn_sal_b.Attributes.Add("id", "hdn_sal_b");
hdn_sal_b.Attributes.Add("name", "hdn_sal_b");
hdn_sal_b.Attributes.Add("type", "hidden");
hdn_sal_b.Attributes.Add("value", Session["user_name"].ToString());
frm.Controls.Add(hdn_sal_a);
frm.Controls.Add(hdn_sal_b);
column1.Controls.Add(frm);
return frm;
}
separate the concerns The Visual part your application shouldn't be affected if you move your app to java or ruby. that's what separate of concerns is.
write the client script in the client, not in the cs file:
$('#<%= hl_process.ClientID %>').click(function(){
...
$('#formId').submit();
// if the button inside the form:
this.form.submit(); // HTML5
// Or:
$(this).closest('form').submit();
// if the button not inside the form :
var class = $(this).attr('class');
$('form.' + class).submit();
});
Use jquery to bind to the click event instead of doing this on the server side:
Submit Me
then in javascript something like:
<script type="text/javascript">
$('.blah').click(function() {
document.forms[0].submit();
});
</script>
Edit:
While you can generate UI elements with codebehind it's not quite the asp.net way. Use repeaters if you must repeat the generation of controls. Actually, creating multiple forms is not the asp.net way either, as it assumes only one form running at the server context and everything else binds to an event on submission. Anyways, it seems you're still learning asp.net and probably coming form PHP or something similar.
To accommodate your request, I'd advice to stay away from from generating JS on the server side. Give different class names to your forms and use the same method above. You don't need a LinkButton to submit the form, a simple anchor <a> fits the bill.
You can use the ClientID property (if you don't use classes), but you must first attach the parent control to the page for the algorithm to kick in.
So, your code would be something like:
protected Control CreateCommForm()
{
...
column1.Controls.Add(frm);
HtmlGenericControl a = new HtmlGenericControl("a");
a.Attributes["onclick"] = "$('#" + frm.ClientID + "').submit();";
a.InnerText = "Submit me";
frm.Controls.Add(a);
return frm;
}
The alternative way (better separation of concerns)
protected Control CreateCommForm()
{
...
column1.Controls.Add(frm);
HtmlGenericControl a = new HtmlGenericControl("a");
a.Attributes["class"] = "submitter";
a.InnerText = "Submit me";
frm.Controls.Add(a);
return frm;
}
And in javascript we find the parent form and submit it (this can be in a static js file):
<script type="text/javascript">
$('.submitter').click(function(
$(this).parents('form').submit();
));
</script>
I created ASP.NET user control with javascript function :
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs" Inherits="BingTranslator.Web.WebUserControl1" %>
<script type="text/javascript">
function example() {
alert('<%=ExampleButton.ClientID%>');
return false;
}
</script>
<asp:Button ID="ExampleButton" runat="server" Text="Example"/>
I want to call "example" function when user move mouse to button, so I added attribute for button:
ExampleButton.Attributes.Add("onmouseover", "example()");
It works well, but when I need two controls on same page I got a problems. ASP.NET generates code with two functions with same name, what is wrong:
<script type="text/javascript">
function example() {
alert('TestControl1_ExampleButton');
return false;
}
</script>
<input type="submit" name="TestControl1$ExampleButton" value="Example" id="TestControl1_ExampleButton" onmouseover="example()" />
<script type="text/javascript">
function example() {
alert('TestControl2_ExampleButton');
return false;
}
</script>
<input type="submit" name="TestControl2$ExampleButton" value="Example" id="TestControl2_ExampleButton" onmouseover="example()" />
And always onmouseover event on any button will call second function. I am able resolve this issue by adding java script code with client Id directly to attriburte onmouseover.
ExampleButton.Attributes.Add("onmouseover", "[Here will be javascript code]");
But it is not very harmonious solution as for me. Please advise, how I can better resolve such issue.
P.S. There will be much more Javascript code, I added two string upper just for example.
I found a solution in another site which allows you to use external file
if (!Page.ClientScript.IsClientScriptIncludeRegistered("key"))
{
string url = ResolveClientUrl("~/Scripts/file.js");
Page.ClientScript.RegisterClientScriptInclude("key", url);
}
You need to register your scripts with ClientScriptManager - this way they can be registered once, regardless of how often the control has been added to the page:
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}
You need to use this.id
$(document).ready(function () {
load_v<%= this.ID %>
});
function load_v<%= this.ID %>(fromclick) {
alert('anything');
}
So that even if you need two or more same controls in the same page they will have different ids.
Hope this Helps! cheers :)