I have done lots of reading up but I don’t understand why this is not working. I am using VS2010 with current updates. I want to Load a Web Page into the C# Web Browser Control (This Application is a Windows Forms Application):
this.webBrowser1.Navigate("https://mydomain/L1/L2/L3/L4/webpage.asp");
this.webBrowser1.PerformLayout();
In my understanding, to call Javascript Functions from C#, one would use:
this.webBrowser1.Document.InvokeScript("passwordReset");
or if one had Parameters to pass:
object[] parameters = new object[3];
parameters[0] = “1”;
parameters[0] = false;
parameters[0] = “3”;
webBrowser1.Document.InvokeScript("passwordReset", parameters);
My Web Page code is as follows. I have shown both methods I have tried. One seems to work, if I insert the Javascript into the page.
I don’t want to work with this method due to limitations I have. I need to be able to call the *.js File as shown:
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>My Test Page...</title>
<script type="text/javascript" language="javaScript">
function passwordReset()
{
alert("You're about to change your password!!");
}
</script>
<script type="text/javascript" src="/L1/L2/Password_Reset.js"></script>
</head>
Please note, I am not including both Javascripts in my page at the same time. I have only included both in this example.
Can someone please explain why this method, when calling on functions in the “Password_Reset.js” file, is not working as desired?
I have tried setting full permissions: [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
and also making this app Com Visible: [System.Runtime.InteropServices.ComVisibleAttribute(true)]
EDIT: What I am trying to achieve, is to be able to run Javascripts after webBrowser1.Navigate("URL"); when they are written into the page code as Follows:
<script type="text/javascript" src="/L1/L2/Password_Reset.js"></script>
EDIT: In Re-Reading my question, I wonder if this issue is a Folder Level problem and the Script is not loading? Can someone advise on this?
The solution was, in the end, very simple, and a little on the obvious side. I am a little embarrased.
Once the Browser Control Document Completed:
webBrowser1.DocumentCompleted +=new WebBrowserDocumentCompletedEventHandler(webBrowserTest_DocumentCompleted);
Event has been called, and when:
webBrowser1.PerformLayout();
has been run, the Javascripts, at this stage has not fully loaded from what I can see. If I set a delay timer up and count a 1000 milliseconds then call my Javascript, the whole thing works perfectly. This is unless, by delaying the calls to my javascript, are in-turn allowing another issue in the background to resolve itself?
I guess the next thing to solve, is why is the DocumentCompleted eventhandler not including the loading of scripts in the way one would expect.
I hope others find this usefull and it saves them the time I spend resolving ths issue.
I'm not sure of what you are trying to accomplish.
However, I suggest you to look at startup script registration methods. If you use them, a JavaScript function will be executed in client browser after html document loading.
Take a look at this article. Maybe you can use it solve your problem.
Related
I have a C# application to access data from a third party website. I'm using WebClient and I call DownloadData and process the bytes(DownloadFile would yield similar results).
This worked fine until recently. Now, more often than not, instead of the desired XML file, I get an html page similar to:
<!-- _localBinding -->
<!-- _lcid="1033" _version="" -->
<html>
<head>
<meta HTTP-EQUIV="Content-Type" content="text/html; charset=utf-8" />
<meta HTTP-EQUIV="Expires" content="0" />
<noscript>
<meta http-equiv="refresh" content="0; url=/_layouts/spsredirect.aspx?noscript=1" />
</noscript>
<script language="javascript" src="/_layouts/1033/init.js"></script>
<script language="javascript" src="/_layouts/1033/core.js"></script>
<script language="javascript">
var requestedUrl = escapeProperly(window.location.href);
STSNavigate("/CustomErrors/ErrorPage.aspx?oldUrl=" + requestedUrl);
</script>
</head>
<body></body>
</html>
I'm stumped as to why this went from consistently working to consistently giving me problems. Sometimes, I can still get the expected XML file. Do you have an idea of what this issue might be and how I can fix it?
It might be worth noting that if I were to click the download link manually in a browser, a javascript window would pop up and close before the file downloads. I'm using WebBrowser to intercept the non-static URL of that popup and pass that link (and headers/cookie information) to WebClient. The link would look something like https://foo.bar/Something.axd?Session=1234vv1234Format=XML
Thanks for your time
It looks like the third-party page is throwing an exception. This could be due to parameters you are passing it, or it could be a problem on their end. The best course of action would be to contact the provider and see what errors are being logged (hopefully they are logging them somewhere). Otherwise you are just going to be guessing at what you are doing wrong.
Is it possible that there are encoded\escaped characters in the session querystring param that are not being handled properly? That would be my first guess since there aren't any real error details.
If it's throwing an error, I'd attempt to collect the HTTP status code, you can do this by using the HttpWebRequest and HttpWebResponse (I believe these pre-dated WebClient). There's tricky ways to still use WebClient and retrieve the status code as well, I'd check the content type as well before you actually download.
In any condition, even if serving an error page, the server should respond with an appropriate HTTP status code. (At least in a perfect world).
I have a ASP .Net MVC4 Web application. In it I have my usual html for the _Layout.cshtml, which in turn loads the default Home/Index. All works fine.
In my index I am also loading a partial view. This works fine too. No probs.
I am using a the UI tools from the following site:
http://www.keenthemes.com/preview/index.php?theme=metronic
The problem is it seems to be primarily HTML4 and not designed for MVC out of the box so I am having to tweak it slightly to get it to work the way I want. (Nothing beyond anything very basic). For example, moving one part out to the index and using Renderbody() to load it so the actual html structure never changes. I have done this a million times to be sure I am not missing any closing tags or anything else that could cause my problem.
Up to this point there is no problem at all. Everything loads as it should.
I continued to create a 2nd View and its partial to extract other parts of the site. As usual, baby steps first. Before extracting any other code, I just used a little "Hello World" in the first page, and a similar string in the partial to be sure it was working. It was.
Now when I type in the url Home/ActionName the whole thing reloads as it should but looks horrible. and I get this error message:
0x800a1391 - JavaScript runtime error: 'jQuery' is undefined
Below is my code which clearly defines it:
<!-- BEGIN CORE PLUGINS -->
<script src="assets/plugins/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
jQuery(document).ready(function ()
{
App.init(); // initlayout and core plugins
_Layout.init();
_Layout.initJQVMAP(); // init index page's custom scripts
_Layout.initCalendar(); // init index page's custom scripts
_Layout.initCharts(); // init index page's custom scripts
_Layout.initChat();
_Layout.initDashboardDaterange(); //Red date range
_Layout.initIntro(); //Pop up messages
});
</script>
It points me to the jQuery(document).ready part when I see the message.
Again, when I load the page normally, it works fine. When I type Home on its own it works fine. Its only when I type Home/AnythingElse that it gives this error message. Even if I type Home/ which should load in the Index file, it gives me this error message.
jQuery is defined, so why is this happening on postback?
Any help is appreciated.
Try setting the src for jQuery to be absolute from the site root:
<script src="/assets/plugins/jquery-1.8.3.min.js" type="text/javascript"></script>
Note the / before assets - when your src path does not start with a / the browser will try and load the asset relative to the current path, so in your example when you add the trailing slash to Home it will try to load jQuery from Home/assets/plugins/...
For me, the MVC bundlers were causing problems (in my case the ui bundler)
Here is the order which worked for me.
<script src="/Scripts/modernizr-2.5.3.js"></script>
<script src="/Scripts/jquery-1.7.1.js"></script>
<script src="/bundles/jquery-ui"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
You need to add the jquery-x.xx.x.js first before the validate.js like this
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
I have many HTML helper in Helpers.cshtml file, but some of the helper (html) need some jquery action, so how do i can call jquery inside helpers.cshtml, is that possible?
i know we can keep the js file in header or particular page, but i do not want to do like that, i want to use jquery or javascript only on the page which loaded particular helper.
anyone have idea on this?
My scenario is, i have list box control, that is properly loading from helper, but i need to apply custom theme to the list box.
Little more Clarity
//in index.cshtml
#Helpers.testListBox("mylist" "1,2,3,4,5,6,7")
//in Helpers.cshtml
#helper testListBox(string listName, string listData){
//...... HTML code .........
//Javascript here?
}
With Web Forms, the framework could automatically include Javascript (once) when certain server controls were used on a page; ASP.Net MVC has no such facility. It sounds like this is what you're missing.
The way to do it is on the client. Look at RequireJS at http://requirejs.org/. This is a client-side library for managing Javascript dependencies. This does what Web Forms did, but better, and it does more. Your master layout will have a script tag like this:
<script src="/Scripts/require.js" type="text/javascript" data-main="/Scripts/main"></script>
This can be the only script tag you include on every page. Everything else can be dynamically loaded only as needed by RequireJS. It's true that you load this on every page, but it's smaller than jQuery, and it earns its place because it does so much for you.
Using your example, let's say you have this markup:
#Helpers.testListBox("mylist" "1,2,3,4,5,6,7")
and it renders HTML and needs jQuery scripting. You would render this:
// HTML for list box here
<script type="text/javascript>
require(['jquery'], function($) {
// Do your jQuery coding here:
$("myList").doSomething().whatever();
});
</script>
The require function will load jQuery, unless it has already been loaded, and then execute your code. It's true that your jQuery snippet is repeated once per use of the HTML helper, but that's not a big deal; that code should be short.
RequireJS manages dependencies effectively; you can have module A, and module B which dependes on A, and module C which depends on B. When your client code asks for module C, A and B will be loaded along with C, and in the correct order, and only once each. Furthermore, except for the initial load of require.js, scripts are loaded asynchronously, so your page rendering is not delayed by script loading.
When it's time to deploy your site on the web server, there's a tool that will examine the dependencies among the Javascript files and combine them into one or a small number of files, and then minimize them. None of your markup has to change at all. While in development, you can work with lots of small, modular Javascript files for easy debugging, and when you deploy, they are combined and minimized for efficiency.
This is much better than what the web forms framework did, and entirely client-side, which in my opinion is where it belongs.
You can put a <script> tag in the helper body.
How about this for an example of a partial view:
#model Member.CurrentMemberModel
#{
var title = "Test View";
}
<script type="text/javascript">
// Javascript goes in here, you can even add properties using "#" symbol
$(document).ready(function () {
//Do Jquery stuff here
});
</script>
#if (currentMember != null)
{
<div>Hello Member</div>
}
else
{
<div>You are not logged in</div>
}
This question is an extension to Showing/Hiding div.
As stated, I found a workaround to prevent a Collapse panel from flashing upon load.
My solution was this:
In header:
function showDivs() {
divMenuContent.style.visibility = 'visible';
divMenuContent.style.display='block';
}
</script>
and panel hidden in div as:
<div id="divMenuContent" style="visibility:hidden; display:none;">
<asp:Panel ID="pnlAddNewContent" runat="server" CssClass="collapsePanel" Width="500px">
</asp:Panel>
</div>
and body load is
onLoad="javascript:showDivs();"
The thing is, it works perfectly on a blank page. But I think when I do a
ClientScript.RegisterClientScriptBlock(this.GetType(), "", sb.ToString());
it doesn't work - as in the panel doesnt collapse/show. The above code does work.
Do you believe the clientScipt conflicts with my javascript to show div? I don't receive any Javascript run errors within browser.
More info: The clientScript is called if its not a postback. I have also tried to call the javascript from the clientscript by adding the following code at the end of it:
sb.Append("\n}\nshowDivs();</script>\n");
But this time I get the following error:
divMenuConent is undefined.
ANy solutions?
If I remember right the RegisterClientScriptBlock injects its JS into the head. Could be that its injecting it above your code. Now that could mean a couple of things depending on what that injected code is doing.
Is it referencing any elements straight away (remember this is in the head so you won't be able to mess with the DOM as it would have loaded it yet, all that stuff needs to be after onload)
Is it referencing divMenuContent which you might only be declaring below it
Is it throwing an error which is stopping the rest of your inpage JS from running.
Use firebug in Firefox to double check you are not getting any funny JS errors and view the source and double check you are not trying to reference anything before you should be.
Also I'd suggest you look into using one of the JS frameworks to allow you to wire up multiple onload events so you don't run the risk of over-writing any previous attached events. This allows you to run multiple function when the page loads (or even better, aka faster, when the DOM loads). I'd suggest MooTools in which case you can do something like this
// You can add as many of these as you like and they will all run :)
window.addEvent( "domready", function() {
// Code to run goes here
});
You can use RegisterStartupScript for this kind Requirement.
i need individual explanation and individual advantages regarding RegisterClientScriptBlock & RegisterStartupScript & responce.write("script");
i got some information like
RegisterClientScriptBlock() methods will inject the script after the form open tag but before page controls
RegisterStartupScript() methods will inject the scripts after page controls but before form close tag.
we can also simply wrie responce.write("script") it aslo include the script.
but i need individual explanation
if any link is available regarding this topic also pls reply me.
If you use the RegisterClientScriptBlock() and you need to reference other javascript methods or html objects that may get injected, you run the risk of them not being created when the script is run. Using the RegisterStartupScript(), as you said, puts the script at the bottom of the page, garanteeing that all objects will have been rendered and created before your script is run.
If you are using either to add a script that is a function like:
<script type="text/javascript>
function myFunc(){
...
}
</script>
Then is doesn't matter, because that function needs to be called explicitly, by something else.
But if you are trying to have a script run after the document loads like:
<script type="text/javascript>
doStuff();
</script>
Then you should use RegisterStartupScript() so you are garanteed that any objects called by you or the functions you call exists.