WebBrowser Control - Invoke Script Problems with JavaScript Button - c#

I am trying to login to a website. I am able to fill out the form correctly with all of the connection information, but I cannot get the page to login. The button is a link without a name or id, so I can't click it directly. I have been working on invokeScript() stuff, but that doesn't seem to work either. This is the button code:
<div style="float:left; width:50px; margin: 0px auto 0px auto; text-align:center;">
<div id="loginBtn">
<a href="#" style="text-decoration:none; font-weight:bold; font-size: 10px; color:#FFFFFF;" onClick="javascript: LoginSubmit(event, true);" tabindex="3">
Log In
</a>
</div>
</div>
How can I click a link like that?
I have tried stuff like this:
webBrowserControl.InvokeScript("LoginSubmit", "true" );
webBrowserControl.InvokeScript("LoginSubmit(event, true)");
and
webBrowserControl.InvokeScript("LoginSubmit", new object[] { new string[] { "event", "true" } });

You may be missing Document, like so:
webBrowserControl.Document.InvokeScript(name, args)
if not try invoking the script with this wrapper method, extract:
private object MyInvokeScript(string name, params object[] args)
{
return webBrowserControl.Document.InvokeScript(name, args);
}
…
int x = 50;
int y = 100;
MyInvokeScript("LoginSubmit",x, y);

Related

How to pass data between different c# and javascript

I have an ascx page with a div, when the div is clicked it calls a JS function and send an int
//HTML
<div style="float: right; margin-right: 150px;" class="innerDivStyle"
onclick="userStartExtend(2)">
<h1 style="margin-top: 50px">Product</h1>
</div>
//JavaScript function
function userStartExtend(num) {}
I need to use the num from userStartExtend function in a c# (file/page/code). I thought about querystring - set in javascript code and get in c# (possible?). Any other ideas ??
To make things clear : the c# code and javascript code dont share the same page.
What one normally does in a case where he wants to pass something from Javascript to .NET he uses eventHandlers, just don't forget to add attributes runat="server" id="DivId" and event handler OnServerClick="DivHandler".
Example:
<div runat="server" id="DivId" OnServerClick="DivHandler" style="float: right; margin-right: 150px;" class="innerDivStyle" onclick="userStartExtend(2)" >
<h1 style="margin-top: 50px">Product</h1>
</div>
then on C# side
public void DivHandler(object sender, EventArgs e)
{
//here sender is your <div> and e is data about 'click' event.
}
UPDATE: It appears that OnServerClick does not work properly ether. Here is workaround
HTML:
<div runat="server" id="DivId" OnServerClick="testMe('param1')" style="float: right; margin-right: 150px;" class="innerDivStyle" onclick="userStartExtend(2)" >
<h1 style="margin-top: 50px">Product</h1>
</div>
JavaScript:
function testMe(params) {
var btnID= '<%=MyButton.ClientID %>';
__doPostBack(btnID, params);
}
Server-side Page_Load:
string parameter = Request["__EVENTARGUMENT"];
if (parameter == "param1")
MyButton_Click(sender, e);
Make your div server side
<div id="serverSideId" runat="server" />
In your C# code, Page_PreRender should have this
int myValue = 2;
serverSideId.OnClientClick = "userStartExtend(" + myValue.ToString() + ")";
Add a hidden Field control in your use control
<asp:HiddenField ID="hdnval" runat="server" Value="" Visible="false">
update your javascript function as this
function userStartExtend(num) {
var myHidden= document.getElementById('<%= hdnval.ClientID %>');
if(myHidden)
{
myHidden.value=num;
}
}
Now use can access this server control at code behind

javascript/jquery modal popup dialog MVC 4 / render partial view

I have been using the DevExpress PopupControl. They look nice and pretty but they do not display the scrollbars on iOS/Android devices. So I want to come up with an alternative. My immediate use is just for displaying a partial view, read only and a close button.
I am not familiar with jquery so I am having a hard time piecing together all the different posts about this topic.
My index.cshtml is a portal with many different partial views. One of the partial views is a list of clients. The client name is a link to client detail. This is where I need the popup dialog.
Partial view with client list (note the link calls a javascript function passing the ID I want to view:
<table style="text-align: left;">
#if ((Model != null) && (Model.Items != null))
{
foreach (WebMVC.Models.VisitDetails p in Model.Items)
{
sTime = p.StartTime.ToString("MM/dd") + " " + p.StartTime.ToShortTimeString().PadLeft(8,'_') + " - " + p.EndTime.ToShortTimeString().PadLeft(8,'_');
<tr>
<td style="width: auto">
#Html.DevExpress().HyperLink(
settings =>
{
settings.Name = "indexHyperLinkClient" + p.VisitID.ToString();
settings.Properties.Text = #p.NameNumZone;
settings.Properties.ClientSideEvents.Click =
string.Format("function(s, e) {{ MethodClient('{0}'); }}", p.Account);
}
).GetHtml()
</td>
</tr>
}
}
</table>
current javascript in index.cshtml that handles the popup:
<script type="text/javascript">
var _clientId;
function MethodClient(clientid) {
_clientId = clientid;
popClient.PerformCallback();
popClient.Show();
}
function OnBeginCallbackClient(s, e) {
e.customArgs["clientid"] = _clientId;
}
<script type="text/javascript">
popClient is the current dialog that I want to replace. I would like the dialog to be a specific height regardless of the content size.
example of the partial view to be displayed in the dialog:
#model WebMVC.Models.ClientDetail
#{
DateTime now = DateTime.Today;
int age = now.Year - Model.Birthdate.Year;
if (Model.Birthdate > now.AddYears(-age))
{
age--;
}
string sBirthdate = Model.Birthdate.ToShortDateString() + " (Age: " + age + ")";
}
<div id="contentDiv">
<span class="display-label">#Html.DisplayNameFor(model => model.NameNumZone):</span>
<span class="display-field">#Html.DisplayFor(model => model.NameNumZone)</span>
<br />
<span class="display-label">#Html.DisplayNameFor(model => model.Sex):</span>
<span class="display-field">#Html.DisplayFor(model => model.Sex)</span>
<br />
<span class="display-label">#Html.DisplayNameFor(model => model.Birthdate):</span>
<span class="display-field">#Html.DisplayFor(model => #sBirthdate)</span>
<br />
<span class="display-label">#Html.DisplayNameFor(model => model.Address):</span>
<span class="display-field">#Html.DisplayFor(model => model.Address)</span>
<br />
</div>
Controller:
public ActionResult Details()
{
string id = "";
if (!string.IsNullOrEmpty(Request.Params["clientid"]))
id = Request.Params["clientid"];
int clientid = 0;
if (id != "")
clientid = Convert.ToInt32(id);
ClientDetail cl;
if (clientid != 0)
ClientDetail cl = GetClientDetails(clientid);
else
ClientDetail cl = new ClientDetail();
return PartialView("ClientPopupPartial", cl);
}
Can I have one popup and render different partial views (maybe by adding a hardcoded param such as area = 1, area = 2 to the method client call)? Or should there be one popup for each area of detail (client, visit, directions...).
Example with a static dialog (No AJAX)
Define a div for your dialog content in a partial view:
#model ClientDetail
<h2>Client Detail</h2>
#Html.DisplayFor(m => m.NameNumZone)
#Html.DisplayFor(m => m.Birthdate)
...
Dialog trigger and partial view:
#p.NameNumZone
<div id="client-detail-modal">
#Html.Partial("ClientDetail", Model.Item)
</div>
Javascript:
$(document).ready(function() {
// setup the dialog
$("#client-detail-modal").dialog({
modal: true,
autoOpen: false,
height: 100,
width: 200
});
// bind the click event
$(".dialog-trigger").on("click", function(event) {
event.preventDefault();
$("#client-detail-modal").dialog("open"); // show dialog
});
});
Now if you have more than one client on a page you'll need a dialog per client. After a few clients it gets ugly. Instead, fill the dialog content dynamically.
Dynamic dialog content (AJAX)
Dialog container for your partial is empty initially:
<div id="client-detail-modal"><!-- Client Partial, empty for now --></div>
Get the partial via AJAX:
$(".dialog-trigger").on("click", function(event) {
event.preventDefault();
var clientId = $(this).data("clientId");
$.ajax({
url: "Client/Details/" + clientId,
type: "GET",
})
.done(function(result) {
$("#client-detail-modal").html(result).dialog("open");
});
});
Dynamic content (No AJAX)
Another way to fill the dialog would be to populate the data attributes of the trigger element then replace content using javascript.
<a href="#" class="dialog-trigger"
data-clientId="#p.Account"
data-birthdate="#p.Birthdate">#p.NameNumZone</a>
$(".dialog-trigger").on("click", function(event) {
var clientId = $(this).data("clientId");
var birthdate = $(this).data("birthdate");
// now replace content with new values
$("span.birthdate").text(birthdate);
});
Put this content in your style sheet
.modalDialog {
position: fixed;
font-family: Arial, Helvetica, sans-serif;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0,0,0,0.8);
z-index: 99999;
opacity:0;
-webkit-transition: opacity 400ms ease-in;
-moz-transition: opacity 400ms ease-in;
transition: opacity 400ms ease-in;
pointer-events: none;
}
.modalDialog:target {
opacity:1;
pointer-events: auto;
}
.modalDialog > div {
width: 80%;
position: relative;
margin: 10% auto;
padding: 5px 20px 13px 20px;
border-radius: 10px;
background: #fff;
background: -moz-linear-gradient(#fff, #999);
background: -webkit-linear-gradient(#fff, #999);
background: -o-linear-gradient(#fff, #999);
}
.close {
background: #606061;
color: #FFFFFF;
line-height: 25px;
position: absolute;
right: -12px;
text-align: center;
top: -10px;
width: 24px;
text-decoration: none;
font-weight: bold;
-webkit-border-radius: 12px;
-moz-border-radius: 12px;
border-radius: 12px;
-moz-box-shadow: 1px 1px 3px #000;
-webkit-box-shadow: 1px 1px 3px #000;
box-shadow: 1px 1px 3px #000;
}
.close:hover { background: #00d9ff; }
and in the code use the following
Open Modal
<div id="openModal" class="modalDialog" data-theme="c">
<div>
X
<h2>Pop up</h2>
<p>Pop up content. You can add your controls and content here</p>
</div>
</div>
this logic worked for me. Hope it works for you also.
Instead of using X for closing it is preferred you navigate to some parent page instead.

How to show a div after postback on a button click?

Here i have a div in which i am showing it during the mouse hover in the master page and after mouse hover three href links will appear in that div .After clicking that href link it is traversing to another page,postback happens and that div is getting hidden in the master page.I need to show that div after that click also.I have used updatepanel and tried it but still it is not working.here is my code
//Div part
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="Update" runat="server">
<ContentTemplate>
<div runat="server" class="divSUBMenu" id="describe" style="width: 700px; height: 20px;
font: Arial, Helvetica, sans-serif;" onclick="show(0)">
</div>
</ContentTemplate>
</asp:UpdatePanel>
//Onhover part
<a href="#" onmouseover="showit(0)">
<img src="Images/Analyze_over.jpg" name="image1" width="84" height="22" border="0"
id="image1" alt="" /></a>
//Javascript for mousehover(working fine)
var submenu = new Array();
submenu[0] = ' <font style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;"><a style="color: #FFFFFF; text-decoration: none;" href="ATrendAnalysis.aspx">Trend Analysis</a> <a style="color: #FFFFFF; text-decoration: none;" href="AEventPerformance.aspx">Event Performance</a> <a style="color: #FFFFFF; text-decoration: none;" href="ACannibalization.aspx">Cannibalization</a> <a style="color: #FFFFFF; text-decoration: none;" href="AHaloEffect.aspx">Halo Effect</a> <a style="color: #FFFFFF; text-decoration: none;" href="AVolumeDecomposition.aspx">Volume Decomposition</a></font></span>';
var delay_hide = 500;
var menuobj = document.getElementById ? document.getElementById("describe") : document.all ? document.all.describe : document.layers ? document.dep1.document.dep2 : "";
function showit(which) {
clear_delayhide();
document.getElementById("describe").style.visibility = 'visible';
thecontent = (which == -1) ? "" : submenu[which];
if (document.getElementById || document.all) {
menuobj.innerHTML = thecontent;
}
else if (document.layers) {
menuobj.document.write(thecontent);
menuobj.document.close();
}
}
and finally the part below is not working during the onclick but this alert is working
function show(which) {
alert("test");
document.getElementById("describe").style.visibility = 'visible';
}
Any suggestion??
EDIT:
This is the href am clicking
<a style="color: #FFFFFF; text-decoration: none;" href="ATrendAnalysis.aspx">Trend Analysis</a>
You have to use ClientScriptManager
http://msdn.microsoft.com/en-us/library/3hc29e2a.aspx
Example:
void Page_Load(object sender, EventArgs e)
{
if(checkDisplayCount.Checked)
{
String scriptText = "";
scriptText += "function DisplayCharCount(){";
scriptText += " spanCounter.innerText = " +
" document.forms[0].TextBox1.value.length";
scriptText += "}";
ClientScriptManager.RegisterClientScriptBlock(this.GetType(),
"CounterScript", scriptText, true);
TextBox1.Attributes.Add("onkeyup", "DisplayCharCount()");
LiteralControl spanLiteral = new
LiteralControl("<span id=\"spanCounter\"></span>");
PlaceHolder1.Controls.Add(spanLiteral);
}
}
Since the div is set to runat=server, you could control this on the server side - setting describe.IsVisible = false initially, and changing it to describe.IsVisible = true post-click.
If for whatever reason this must be done on the client, due to reliance on other scripts or something, then make sure you're looking for the control by using the correct identifier - it could be, depending on the version of ASP.NET you're using, that the control is prefixed with ctl00_x. In fact, even in newer versions of ASP.NET (above .NET 3.5), I think the UpdatePanel might explicitly alter the identifiers of its elements using a prefix so as to keep track of what it contains, don't quote me on that though. Check the rendered markup output on the page to check this.

HtmlElement.invoke(“click”) doesn't work

I'm trying to create an application that can fill html form automatically using WebBrowser control(C#). There is a option list on the web page and I can get corresponding elements in the drop down box. But when I call the invokemember("click") methods, there is no responce.Below in the selection element of HTML
<div>
class="ddlcont" style="display: block; width: 150px; top: 414px; left: 790.75px;">
<a class="select" v="0" href="javascript:;">Not </a>
<a v="419000" href="javascript:;">insure</a></div>
Here is my codes,I find ScrollIntoView and Focus method is ok
HtmlElementCollection element_div=currentWindow.Frames[0].Document.GetElementsByTagName ("div");
foreach (HtmlElement item in element_div)
{
if (item.GetAttribute("classname") == "ddlcont" && item.Children.Count !=0)
{
item.Children[1].ScrollIntoView(true);
item.Children[1].Focus();
item.Children [1].SetAttribute("selected", "true");
item.Children [1].InvokeMember("Click");
}
}
I am appreciate that if anyone can help me to solve the problem. Thanks for your help!
You may have pasted wrong, but in your example div doesn't have a class.
Look:
<div>
class="ddlcont" style="display: block; width: 150px; top: 414px; left: 790.75px;">
should be
<div
class="ddlcont" style="display: block; width: 150px; top: 414px; left: 790.75px;">
(no > on the first line)
Try something like this instead:
Button1.GetType().GetEvent("OnClick").GetRaiseMethod().Invoke(Button1, EventArgs.Empty);
You may need to tweak the syntax a little bit, but this should put you on the right path.

'Please wait' screen between pages in C# ASP.NET. Best practice?

I have a gridview with some imagebuttons, each of which kicks off a report page for that item. The report take 10-15 seconds to run, so I'd like a popup 'Generating report, please wait' type thing. I can think of a few ways but would like the opinion of those more experienced than I. The options I was considering:
a) link my imagebutton to an intermediate page that says 'please wait', and then refer it onto the report page from there. Seems a bit clunky
b) Investigate using jquery or similar. I have telerik controls, they have a few things but it isn't clear if any are suitable.
c) Define some kind of CSS layer with a please wait warning on it, and make it visible as part of the button's onclick event
d) Look into jquery or similar
Any thoughts?
Thanks!
I use Div with transparency, and its pretty cool and simple. Give it a try.
<div id="ModalPopup" style="visibility: hidden;">
<div style="position: fixed; width: 100%; height: 100%; z-index: 10002; background-color: Gray;
filter: alpha(opacity=70); opacity: 0.7;">
</div>
<table style="position: fixed; width: 100%; height: 100%; z-index: 10003;">
<tr>
<td align="center" valign="middle">
<div style="color: Black; font-weight: bolder; background-color: White; padding: 15px;
width: 200px;">
<asp:Image ID="Image3" runat="server" ImageUrl="~/Images/progress.gif" />
Procesando....
</div>
</td>
</tr>
</table>
</div>
To display the div, use this JavaScript:
document.getElementById('ModalPopup').style.visibility = 'visible';
I have the exact same problem before but I found the AJAX Server Control UpdateProgress very useful. Here's a link to UpdateProgress Control.
you can have an <iframe> on the page, of which its style is set to display:none. a button (which you will use to execute an action) will perform a javascript function that will set the style of the <iframe> to display:block on click.
please wait on page load in js can be used in any language give a try
in body place this code
<body>
<div id='loadingmsg' style='display: none;'></div>
<div id='loadingover' style='display: none;'></div>
</body>
in css
#loadingmsg {
width:100%;
height:100%;
position:fixed;
z-index:9999;
background:url("assets/img/loaders/load10.gif") no-repeat center center rgba(255,255,255,0);
}
#loadingover {
background: #23351f;
z-index: 99;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=80)";
filter: alpha(opacity=80);
-moz-opacity: 0.8;
-khtml-opacity: 0.8;
opacity: 0.8;
}
js
<script>
document.onreadystatechange = function () {
var state = document.readyState
if (state == 'interactive') {
showLoading();
}
else if (state == 'complete') {
hideLoading();
}
}
function showLoading() {
document.getElementById('loadingmsg').style.display = 'block';
document.getElementById('loadingover').style.display = 'block';
}
function hideLoading() {
document.getElementById('loadingmsg').style.display = 'none';
document.getElementById('loadingover').style.display = 'none';
}
</script>

Categories

Resources