WebView1.InvokeScript("eval", args);
I want to know whats the meaning of the word "eval". In MSDN library it says its the name of the script. But when I type something else instead of "eval" the code does not work. So whats the meaning of eval ? and what are the other words I can use instead of eval ?
It's the name of a (most commonly JavaScript) function within your HTML code. eval is just a predefined JavaScript function.
But this can be anything:
// HTML code
<html>
<script>
function alertme(name) {
alert('My name is: ' + name);
}
</script>
</html>
// C# code
public void Test() {
WebView1.InvokeScript("alertme", "Inigo Montoya");
}
This will show you a pop-up on your webpage printing the string "My name is Inigo Montoya".
Related
How can I format my own attribute in the codebehind?
The idea is to overwrite CSS inline style so I added a property to my Model.
public string GetBannerBackgroundStyle
{
get
{
return !string.IsNullOrEmpty(GetBannerImageMediaUrl) ? string.Format("style=background-image: url('{0}')", GetBannerImageMediaUrl) : string.Empty;
}
}
In the view I simply set the property on the HTML
<div class="anything" #Model.GetBannerBackgroundStyle></div>
The output however is scrambled. It generates something but not properly as if the quotes weren't closed.
Any better ideas?
Thanks in advance!
UPDATE:
public HtmlString GetBannerBackgroundStyle
{
get
{
return new HtmlString(!string.IsNullOrEmpty(GetBannerImageMediaUrl) ? string.Format("style=background-image: url('{0}')", GetBannerImageMediaUrl) : string.Empty);
}
}
This didn't seem to work :s
UPDATE2:
public IHtmlString GetBannerBackgroundStyle
{
get
{
return new HtmlString(!string.IsNullOrEmpty(GetBannerImageMediaUrl) ? string.Format("style=\"background-image: url('{0}')\"", GetBannerImageMediaUrl) : string.Empty);
}
}
This did work ^^
From MSDN:
The Razor syntax # operator HTML-encodes text before rendering it to the HTTP response. This causes the text to be displayed as regular text in the web page instead of being interpreted as HTML markup.
That's where you can use Html.Raw method (if you don't want/can't change your property to return an HtmlString, please remember that right way to do it is that one as suggested by SLaks):
Use the Raw method when the specified text represents an actual HTML fragment that should not be encoded and that you want to render as markup to the HTTP response.
<div class="anything" #Html.Raw(Model.GetBannerBackgroundStyle)></div>
That said I wouldn't put that logic inside your model. An helper method, some JavaScript...but I wouldn't mix styling with data. In your example it should be:
<div class="anything"
style="background-image: url('#Model.GetBannerImageMediaUrl')">
Please note that your code was also wrong because you're missing quotes for HTML style attribute:
if (!String.IsNullOrEmpty(GetBannerImageMediaUrl))
return String.Empty;
return String.Format("style=\"background-image: url('{0}')\"", GetBannerImageMediaUrl);
---^ ---^
You need to make your property return an IHtmlString to tell Razor to not escape it.
First, however, you need to properly escape it yourself, in case the URL has tags or quotes.
How about the code snippet below?
<div class="anything" #(Model != null && !string.IsNullOrWhiteSpace(GetBannerImageMediaUrl)
? "style=background-image: url('" + GetBannerImageMediaUrl + "')"
: string.Empty)></div>
<%--Confirmation Box--%>
<script type="text/javascript" language="javascript">
function alertbox() {
if (confirm("Are you sure?") == true)
{
document.getElementById('<%= hdnYesNo.ClientID %>').value = "YES";
}
else
{
document.getElementById('<%= hdnYesNo.ClientID %>').value = "NO";
}
}
</script>
How to rewrite this code in C# as codebehind? I would like have a confirm box with yes or no buttons.
protected void Page_Load(object sender, System.EventArgs e)
{
string csName = "PopupScript";
Type csType = this.GetType();
ClientScriptManager csm = Page.ClientScript;
if (!csm.IsStartupScriptRegistered(csType, csName)) {
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("function alertbox() {");
sb.Append("if (confirm('Are you sure?') == true) ");
sb.Append("{");
sb.Append("document.getElementById('" + hdnYesNo.ClientID + "').value = 'YES';");
sb.Append("}");
sb.Append("else");
sb.Append("{");
sb.Append("document.getElementById('" + hdnYesNo.ClientID + "').value = 'NO';");
sb.Append("}");
sb.Append("</script>");
csm.RegisterStartupScript(csType, csName, sb.ToString());
}
}
you can use like this way
Page.ClientScript.RegisterStartupScript(this.GetType(), "Confi", "if(confirm('Are you sure?') == true){ document.getElementById('txtValue').value ='YES';}else{document.getElementById('txtValue').value ='NO';}", true);
You can use ClientScriptManager class and its methods, for example RegisterClientScriptBlock. Depends on when you want the javascript to execute.
See details here:
http://msdn.microsoft.com/en-us/library/System.Web.UI.ClientScriptManager_methods.aspx
You need javascript for this, it's not possible in code behind. Code behind is run on the server before the page is sent to the user, javascript is run on the user's computer.
If you want to get access to their answer in code behind (possible and straightforward), you can use ajax or you can postback.
If you want to have this popup to come up when you press on a .Net asp:button control, then you can put a javascript function in the "OnClientClick" attribute of the control.
EDIT: If you need help with any of the above, let us know and help will be provided :).
EDIT2: Due to the discussion below, I guess I should clarify: You can (obviously) construct javascript on the server side before passing it to the client, but the example you gave is NOT a case where you should be doing that (an example of where this might be a good idea would be a script that has variables read from a database or something similar that doesn't need to be dynamic between page loads).
another option is to create the script in the /View folder and user razor for generating the script.
then you could point to the page in the tag like
<script src="~/ScriptGenerator/MyScript" />
for pointing the controller ScriptGeneratorController that expose the action MyScript
So I'm fairly new to the .NET framework, but what I'm trying to do is execute the following jQuery code:
$(document).on('click', 'a[data-link]', function () {
var $this = $(this);
url = $this.data('link');
$("#imagePreview").load("imageProcess.aspx?"+url);
where url holds something like "model=2k01&type=black&category=variable".
Unfortunately this doesn't work, becuase when I do something as simple as a Response.Write() in the aspx file, the div tag imagePreview doesn't do anything. However, removing the ? + url part works, but then I can't send any data over to the aspx file. I'm doing it this way because every link a[data-link] has different data that's being sent over, and I need to find a dynamic way to achieve this. Any suggestions would be much appreciated.
UPDATE:
Here is the part in my html code that is generating the url stuff:
<a class='modelsBlue' href = '#' data-link='model=" + $(this).find('model').text() + "&type=" + category + "'>" + $(this).find("model").text() + "</a>
and #image preview is in my code as:
<div id = "imagePreview"></div>
When I try to run the code above, i get the following error which seems to be coming from the jQuery.js file:
Microsoft JScript runtime error: Syntax error, unrecognized expression: &type=AutoEarly
Here is the imageProcess.aspx.cs file, which right now is just outputting all images in the directory:
namespace ModelMonitoring
{
public partial class imageProcess : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("test");
foreach (var f in Directory.GetFiles(Directory.GetCurrentDirectory()))
{
Response.Write(f);
Response.Write("<br />");
}
}
}
}
SECOND UPDATE:
I don't get the error running in chrome or firefox, but the files are not being output.
Turns out it was a whitespace issue. I had to add a wrapper around:
$(this).find('model').text()
to read:
$.trim($(this).find('model').text())
becuase the xml file I was reading from had whitespace around the model name. Thanks to anyone who replied!
I need to grab inline script tags inside html pages.
The regex will eventually be driven from c#.
Now I am using Expresso for test purpose.
The following is the best for now:
.*<script.*\r\n(.*\r\n)*\s*</script>
i.e.
.*<script catch the script tag
.*\r\n catch anything till the end of line
(.*\r\n)* catch other lines of the script
\s*</script> catch the closing script, with any indentation before
It grabs ALL the stuff between the first tag, inculding html and other script tags.
Two scripts on the same line will break your regex. Try it on the source of the page with your question.
Parsing HTML with regex is not a very good idea (there is a link in the comment to your question which answers why the <center> cannot hold); use HTML parser instead.
The next code snippet selects the <script> nodes by using HtmlAgilityPack:
var doc = new HtmlDocument();
doc.Load(html);
var scripts = doc.DocumentNode.SelectNodes("//script");
Isn't this is simplier than regex?
Depending on who you ask, you have different problems. Either your problem is, you use regex on html, or your quantifiers are too greedy.
I don't know your problem you want to solve, but chances are good, that your solution should be to use a html parser.
If you want to stick to regex, then use the ungreedy version of the quantifier *?. Your regex would then look something like this
.*<script.*\r\n(.*\r\n)*?\s*</script>
that means it would match as less rows as needed till the first closing tag.
How about enabling "dot matches all" and using something simple:
<script\b[^>]*>(.*?)</script>
Remember that matching is not the same as capturing. This should capture ($1) what's in between the tags. I did a quick test using http://regexpal.com/
Using bosinski.com/regex in Eclipse (I know it's not C#) here's my test file (followed by results):
<html>
<SCRIPT LANGUAGE="JavaScript"><!--
function demoMatchClick() {
var re = new RegExp(document.demoMatch.regex.value);
if (document.demoMatch.subject.value.match(re)) {
alert("Successful match");
} else {
alert("No match");
}
}
// -->
</SCRIPT>
<script language="fred">
this is the second set of code
</script>
</html>
Results of the regex match:
Found 2 match(es):
start=8, end=275
Group(0) = <SCRIPT LANGUAGE="JavaScript"><!--
function demoMatchClick() {
var re = new RegExp(document.demoMatch.regex.value);
if (document.demoMatch.subject.value.match(re)) {
alert("Successful match");
} else {
alert("No match");
}
}
// -->
</SCRIPT>
Group(1) = <!--
function demoMatchClick() {
var re = new RegExp(document.demoMatch.regex.value);
if (document.demoMatch.subject.value.match(re)) {
alert("Successful match");
} else {
alert("No match");
}
}
// -->
start=277, end=344
Group(0) = <script language="fred">
this is the second set of code
</script>
Group(1) =
this is the second set of code
Try this
<(?<tag>script*)[^>]*>(?<content>.*?)<\/\k<tag>>
Replace the word script after <tag> with another element name and you can use it for others too.
I have a parameter for a method, that should be a string and I can't come up with how to <% *.ClientID %> to the thing as a variable like that. Since its a variable i can't wrap it in quotes since it will be taken literally and when I use the parameter like a variable (as you're supposed to) i get an ASP error saying it doesn't exist in the context (reading it literally).
Any Clues?
thanks guys
Code Sample
function next(currentControl, maxLength, nextControl) {
if (document.getElementById( currentControl<%=.ClientID %>).value.length >= maxLength) {
document.getElementById( nextControl<%=.ClientID %>).focus();
}
return false;
}
Call Sample
wValCode.Attributes.Add("onkeyup","next('wValCode','3','wValThree')");
I know probably a primitive way of adding the attribute, but its how it was explained to me. I picked up ASP on the fly so don't be too hard on me ;)
Static HTML
<input name="ctl00$ContentPlaceHolder2$wValThree" type="text" id="ctl00_ContentPlaceHolder2_wValThree" style="width:33px;">
That is the only related reference I can find in the static html. Would it have been added in one of ASPs convoluted js files?
Given you're binding the key events from code behind, you can just reference the client IDs at the time that you're doing the binding:
wValCode.Attributes.Add("onkeyup","next('" + wValCode.ClientID + "', '3', '" + wValThree.ClientID + "')");
Then, you already have the client IDs passed as parameters to the javascript function
function next(currentControl, maxLength, nextControl) {
if (document.getElementById(currentControl).value.length >= maxLength) {
document.getElementById(nextControl).focus();
}
return false;
}
An even better option is to pass a reference to the calling object as the first parameter, using the this keyword:
//code behind
wValCode.Attributes.Add("onkeyup","next(this, '3', '" + wValThree.ClientID + "')");
//javascript function
function next(currentControl, maxLength, nextControl) {
if (currentControl.value.length >= maxLength) {
document.getElementById(nextControl).focus();
}
return false;
}
Try moving the dot outside the ASP.NET tag:
currentControl.<%= ClientID %>