Enabling Javascript Scripts in my C# code on IIS - javascript

I have some Javascript scripts in my ASP code that isn't working when I host it on Information. I tried enabling static content and setting Authentication to Anonymous Authentication. I don't have any separate JS files that I need to run, but .js is also enabled on MIME.
protected void GetDateCal_SelectionChanged(object sender, EventArgs e)
{
if (Request.QueryString["textbox"] != "")
{
string strScript = "<script>window.opener.document.forms[0].ctl00_ContentPlaceHolder1_" + Request.QueryString["textbox"].ToString() + ".value = '";
strScript += GetDateCal.SelectedDate.ToString();
strScript += "';window.opener.document.forms[0].submit();self.close();";
strScript += "</" + "script>";
Page.ClientScript.RegisterClientScriptBlock( this.GetType(), "Calendar_ChangeDate", strScript);
}
}

I would either use the "true" tag to automatic surround your js code with script tags.
And, any "" character in a c# string will be escaped, so use # for your strings.
eg:
string strScript = "<script>window.opener.document.forms[0].ctl00_ContentPlaceHolder1_" + Request.QueryString["textbox"].ToString() + ".value = '";
strScript += GetDateCal.SelectedDate.ToString();
strScript += "';window.opener.document.forms[0].submit();self.close();";
strScript += #"</" + "script>";
Page.ClientScript.RegisterClientScriptBlock( this.GetType(), "Calendar_ChangeDate", strScript);
or, consider dropping the script tags, and use this:
string strScript = "window.opener.document.forms[0].ctl00_ContentPlaceHolder1_" + Request.QueryString["textbox"].ToString() + ".value = '";
strScript += GetDateCal.SelectedDate.ToString();
strScript += "';window.opener.document.forms[0].submit();self.close();";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Calendar_ChangeDate", strScript,true);
So, "" in any string tends to be ignored, or escaped.
Use # for such strings, but probably better is to simple include the true tage in the Register script block, and it will surround the js code with script tags for you.

Related

bootbox.alert not working from code behind

I am importing data to DB from excel using bootstrap file uploader. After data import I need to show a message to user. So I have below code
string strScript = "bootbox.alert('" + Resources.Resource.Success_SaveUserInfo + "');";
Page.ClientScript.RegisterStartupScript(this.GetType(), "UserSave", strScript, true);
But it is not working. Page get freeze instead of alert. But if I use below code it work.
string strScript = "alert('" + Resources.Resource.Success_SaveUserInfo + "');";
Page.ClientScript.RegisterStartupScript(this.GetType(), "UserSave", strScript, true);
I have already added bootbox.min.js. So it is not issue.
You can do like this
string strScript = "<script type = 'text/javascript'>bootbox.alert('" + Resources.Resource.Success_SaveUserInfo + "');</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "UserSave", strScript, true);
OR
Call javascript function it's highly recommended and reusable as well
Page.ClientScript.RegisterStartupScript(this.GetType(), "UserSave", CustomalertFunction('" + Resources.Resource.Success_SaveUserInfo + "'), true);
and write a javascript function
function CustomalertFunction(message)
{
bootbox.alert(message);
}

How the display the string with tags like "<para>", <emphasis> in UIwebview in correct format?

I just a parsed a response from webservice, from the response I've to show the received data for a particular key in UIWebview. The data that have to show in Uiwebview contains some special tags like , and etc., Please advise how to do it?
Note1:
We don't have emphasis tag in html tags:
http://www.w3schools.com/tags/
so browser Can not understand the code. but you can handle it in 2 way.
Add some css to the current tag.
emphasis{ font-style: italic; }
Replace it with tag which is known by browser
You can add some CSS codes to the UIWebView and format them as you like.
The HTML Tag are the tags that you have received from web service. the baseURL is working for Images or relative links. for example if you have
<a href='pica.jpg'>mypic</a>
and baseurl is
http://example.com
the final url will be
http://example.com/pica.jpg
and if it is in your Document of application you can use:
func getBaseUrl() -> NSURL{
var pref = prefrences()
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true)
let fileManager = NSFileManager.defaultManager()
let docsDir = dirPaths[0] as! String // Document folder of application
let url = NSURL(fileURLWithPath: docsDir, isDirectory: true)
return url!
}
this function return a directory from root.
let baseURL = NSURL(string: "http://thebasepath.com/files")
var htmlContentTemplate =
"<!DOCTYPE html >" +
"<html dir=\"ltr\" " +
" <head>" +
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" +
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />" +
" <style>" +
" emphasis{ font-style: italic; }" +
" </style>" +
" </head>" +
" <body dir=\"rtl\" >" +
" <div>%1$s</div>" +
"<script>\n" +
"window.onload= function()\n" +
"{\n" +
"// your javscript code can be here"
"}" +
"</script>" +
" </body>" +
"</html>";
var final = htmlContentTemplate.replace("%1$s", withString: "your html in body tag")
var data = final.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false);
webView.loadData(data, MIMEType: "text/html", textEncodingName: "UTF8", baseURL: baseURL)
to add Replace function to String Data type add below code. the below code can be added to any swift file.
extension String
{
func replace(target: String, withString: String) -> String
{
return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
}
}

Passing javascript parameter from codebehind error

I use this script to call a javascript from codebehind.
ClientScript.RegisterStartupScript(this.GetType(), "Exist", "<script language='javascript'>ConfirmRedirect('" + url + "','" + msg + "');</script>", true);
and my javascript code is
function ConfirmRedirect(url,msg)
{
alert(msg);
window.location.href = url;
}
Am getting ')' expected error.
What am missing here? If am calling javascript without paramters then it is working.
Remove the Script tag and it will work, this worked for me:
ClientScript.RegisterStartupScript(this.GetType(), "Exist", "ConfirmRedirect('" + url + "','" + msg + "');", true);
View the HTML source and include it in your question/post.
You have probably just not escaped the msg enough. It can for example not contain single quotes ' or line breaks.
UPDATE
A simple solution would be to escape all single quotes using Replace().
ClientScript.RegisterStartupScript(this.GetType(), "Exist", "<script language='javascript'>ConfirmRedirect('" + url + "','" + msg.Replace("'", "\'") + "');</script>", true);
Probably the msg parameter contain symbols like the '
Then the code will be something like
<script language='javascript'>
ConfirmRedirect('/myurl/somthing.aspx','Here's my message');
</script>
And there wait for the close parenthesis.
Replace your msg varriable. Use this one---
ClientScript.RegisterStartupScript(this.GetType(), "Exist", "javascript:ConfirmRedirect('" + url + "','" + msg.Replace("'","") + "');", true);

NS_ERROR_XPC_BAD_CONVERT_JS with document.write

I'm pulling in a 3rd party JavaScript file which makes use of document.write, but what's being written needs to be manipulated - preferably before it hits the page. What I've come up with is the following:
// Hijack document.write to buffer all output...
var dwrite = document.write;
var hijacked = '';
document.write = function(content) {
hijacked += content;
};
// Call the script...
dwrite("<script type='text/javascript' src='http://www.example.com/file.js'></script>");
// Manipulate the output...
hijacked
.replace(/a/gi, '4')
.replace(/e/gi, '3')
.replace(/i/gi, '1')
.replace(/o/gi, '0');
// Write the output into the page...
dwrite(hijacked);
// Restore document.write and free our buffer...
document.write = dwrite;
hijacked = null;
With this, I'm getting NS_ERROR_XPC_BAD_CONVERT_JS wherever I attempt to call dwrite. Can anyone offer a suggestion on why this is happening? I don't see why calling document.write through a different name would blow up.
UPDATE I'm seeing this in Firefox 4.0.1.
I tried this and it worked. Basically I replaced document.write after using it.
document.write(""
+ "<script>"
+ "var hijacked = '';"
+ "var dw = document.write;"
+ "document.write = function(content) { hijacked += content; }"
+ "<" + "/script>"
+ "<script type='text/javascript' src='test.js'><" + "/script>"
+ "<script>"
+ "document.write = dw;"
+ "dw = null;"
+ "document.write(hijacked.replace(/e/gi, '4'));"
+ "<" + "/script>");

Sharepoint Custom WebPart Startup Script

Okay, I've gotten a unique issue I've been trying to solve for two days.
I have System.Web.UI.WebControls.WebParts.WebPart control I am building a custom Sharepoint View with. Almost everything I want done is working except one little issue. I need to use Javascript to Format Date and Currency fields. The Client wants DateTime fields to be mm/dd/yyyy and currency have $ and commas where appropriate.
This is easy enough in javascript on a regular aspx page. I just wrote the functions and on page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridFieldDAO dao = new GridFieldDAO();
myGrid.DataSource = dao.getItems();
myGrid.DataBind();
}
GetBuildFormattingScript();
}
private void GetBuildFormattingScript()
{
string script = "<script type=\"text/javascript\">";
script += " FormatByRows(\"" + myGrid.ClientID + "\",2);";
script += " FormatByRowsDate(\"" + myGrid.ClientID + "\",1);";
script += "</script>";
if(!ClientScript.IsClientScriptBlockRegistered("DoFormatting"))
ClientScript.RegisterStartupScript(typeof(string), "DoFormatting", script);
string script2 = " <script type=\"text/javascript\">"+
"var prm = Sys.WebForms.PageRequestManager.getInstance(); "+
"prm.add_beginRequest(BeginRequestHandler); "+
"prm.add_endRequest(EndRequestHandler); "+
"function BeginRequestHandler(sender, args) "+
"{ }"+
"function EndRequestHandler(sender, args) "+
"{ FormatByRows(\"" + myGrid.ClientID + "\",2); "+
" FormatByRowsDate(\""+myGrid.ClientID+"\",1);}</script> ";
if (!ClientScript.IsClientScriptBlockRegistered("DoUpdateFormatting"))
ClientScript.RegisterStartupScript(typeof(string), "DoUpdateFormatting", script2);
}
My issue in that on the OnLoad of the WebPart the grid I am wanting to update doesn't exists... so I have to add code to the OnPreRender.
Well, the WebPArt loads and the Javascript doesn't fire... so I click refresh and it does fire. Can anyone help me get the code working on the inital WebPart Load? Has anyone been able to get server side script to work this way in SharePoint?
Thanks,
Mike V
For this, you can take advantage of _spBodyOnLoadFunctionNames:
string script = "<script type=\"text/javascript\">";
script += " function FormatDataGridRows() {";
script += " FormatByRows(\"" + myGrid.ClientID + "\",2);";
script += " FormatByRowsDate(\"" + myGrid.ClientID + "\",1);";
script += " }";
script += " _spBodyOnLoadFunctionNames.push('FormatDataGridRows');";
script += "</script>";
Edit
To test, put the following code in a Content Editor web part on your page:
<script type="text/javascript">
function SayHello() {
alert('hello world!');
}
_spBodyOnLoadFunctionNames.push("SayHello");
</script>

Categories