Pass 2 arguments in Handler javascript function in codebehind - javascript

I am trying to pass 2 parameters in Handler call in codebehind but I can't get it to work. Here is my code:
X.Msg.Confirm("Confirm", "The field has " + dependency.Count() + " dependent fields. Are you sure you want to proceed? (The dependent fields will be deleted also)", new MessageBoxButtonsConfig
{
Yes = new MessageBoxButtonConfig
{
Handler = "App.direct.UC.DoYesDeleteDepField('" + fieldname + "," + dependency + "')", //ERROR LINE
Text = "Yes"
},
No = new MessageBoxButtonConfig
{
Handler = "",
Text = "No"
}
}).Show();
Error:
System.ArgumentException: DirectMethod: 'DoYesDeleteDepField', The parameter 'dep' is undefined at Ext.Net.DirectMethod.Invoke(Object target, HttpContext context, ParameterCollection args) at Ext.Net.DirectMethod.Invoke(Object target, ParameterCollection args) at Ext.Net.ResourceManager.RaisePostBackEvent(String eventArgument)
[DirectMethod]
public void DoYesDeleteDepField<T>(string fieldname, List<MyDependenciesClass> dep)
{....

You are passing:
App.direct.UC.DoYesDeleteDepField('fieldname,dependency')
the way you written it.
To pass this:
App.direct.UC.DoYesDeleteDepField('fieldname', 'dependency')
you should draw the line like this:
"App.direct.UC.DoYesDeleteDepField('" + fieldname + "', '" + dependency + "')"

For further information on this answer: the initial parameters were being read as a string, thus the javascript threw 'undefined'.
The solution works due to String Concatenation, which is a very important concept on OOP.
For more on string concatenation consult: How to Concatenate Multiple Strings (C# Programming Guide)

Related

Passing json object from Android/iOS native to javascript

Is there any way to pass JSONObject from android to javascript. We are using WebView.evaluateJavascript mehtod and are able to send only String type object. In JS if we are checking the method paramter;s typeof(data) then it is displaying as string but in iOS it displays typeof(data) as OBJECT.
In both android and iOS we are passing String and NSString.
JS method is:
response: function(id, err, data) {
var dataObj;
if(typeof(data) == 'string' ){
dataObj = JSON.parse(data || '{}');
}
}
Android call:
String responseStr = "{\"ok\":\"ok\"}";
String nativeToWebMethod = "javascript:window.nativeService.response("1",'','"+responseStr+"')";
webView.evaluateJavascript(nativeToWebMethod, null);
Just send it as if you were loading a url:
private void loadJS(String jsonResponse){
mWebView.loadUrl("javascript:" + "(function(){" + "yourJsMethodName" + "(" +jsonResponse + ");" + "})()");
}
This will execute a JS Code that will call a function called yourJsMethodName and will pass the JSON as parameter.
Consider execute the last code in the Main Thread
I find out the issue, it was in the way I was sending data:
String nativeToWebMethod = "javascript:window.nativeService.response("1",'','"+responseStr+"')";
should be replaced with
String nativeToWebMethod = "javascript:window.nativeService.response("1",'',"+responseStr+")";
removed single quote around the responseStr.

pass multiple arguments __doPostBack

Is it possible to pass multiple arguments in the __doPostBack call?
I Know how I use one arrgument
__doPostBack('Service', $("input[name=celservice]:checked").val());
and in code behind vb.net
If eventTarget = "Service" Then
'Something
EndIf
but how when I use two arguments
We have created our own library to pass data from web page to ASP.NET. Without getting too much into details, the javascript code wraps info into an XML stream (you can use JSON just as well) that is then parsed on the server.
At its core, our javascript object looks something like this:
function MyArgs() {
var args = '';
this.add = function (id, value) {
args += ('<param id="' + encodeURI(id) + '" value="' + encodeURI(value) + '" />');
};
this.output = function () {
return '<request>' + args + '</request>';
};
}
And we use it like this:
var args = new MyArgs();
args.add("param1", "value A");
args.add("param2", "Value B");
__doPostBack("YOUR_SERVICE", args.output());
We like it because we are quite comfortable with XML data, but you may as well use JSON or URL encoding. The logic is the same: you create a stream that you can parse on the server.
This technique is also useful the other way around, server to client, especially as a response to AJAX requests.
I hope this may be of help to you :)
You can wrap your multiple results in an object, like so:
var result = {
celservice: $("input[name=celservice]:checked").val(),
somethingElse: true
}
then
__doPostBack('Service', result);

Calling JS Function From C# Not Working

Afternoon,
I have been able to call JavaScript functions from my C# before and it worked fine. For some reason this time the function is not getting hit when i breakpoint the code.
So this is my C# method.
public void tester()
{
string returnResult = HttpContext.Current.Session["result"].ToString();
Page.ClientScript.RegisterStartupScript(this.GetType(), "alerify", "alerify('" + returnResult + "');", true);
//ScriptManager.RegisterStartupScript(this, this.GetType(), "alerify", "alerify(" + returnResult + ");", true);
}
You can see that i have tried different methods but the function is still not getting hit.
This is the JavaScript function i want to call.
function alerify(e) {
alert(e);
if (e == "InvalidDates") {
alertify.error("gfgsdggfsdgfsdfd");
}
}
I am thinking that i am missing somthing but i just don't know what.
As it's a string value it needs apostrophes (or quotation marks) to be a string literal in the JavaScript code:
... "alerify('" + returnResult + "');" ...

How do I create a line break in a JavaScript string to feed to NodeJS to write to a text file?

I've created a simple HTML page that takes some input from the user to store on a server to be retrieved later -- this is how the text is treated when the user clicks a submit button (I've placed numbered comments under the key lines but provide the surrounding code for context):
var origText = $('#input-field').val(),
// 1. GETS WHATEVER USER TYPED INTO INPUT FIELD
jsonText = '{ "text": "' + origText + '" }',
// 2. WRAPS IT AN OBJECT STRING
ajaxText = encodeURIComponent(jsonText);
// 3. ENCODES THE STRING FOR USE WITH AJAX
$.ajax({
url: 'http://localhost:8124/',
data: 'save=' + ajaxText + '&fn=save',
// 4. THE ENCODED STRING IS ADDED TO THE QUERY SECTION OF THE AJAX REQUEST
dataType: "jsonp",
cache: false,
timeout: 5000,
success: function(data) {
$("#input-ready").html(data.save.text);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
The request is sent to a NodeJS server I am running locally, which (within the http.createServer callback) does the following:
var queryObj = url.parse(req.url, true).query;
// 1. GET THE QUERY PART OF THE REQUEST/URL AS AN OBJECT
res.writeHead(200, {'Content-Type': 'application/javascript'});
// 2. PREPARE SERVER'S RESPONSE AS JAVASCRIPT
queryObj.fn = queryObj.fn || '';
queryObj.save = queryObj.save || '';
queryObj.callback = queryObj.callback || '';
// 3. ENSURE THE PROPERTIES NEEDED ARE DEFINED, EVEN IF FALSE-Y
if (queryObj.fn === 'save') {
// 4. IF THE REQUEST IS TO SAVE THEN WRITE THE USER INPUT AS OBJECT TO A TEXT FILE
fs.writeFile('jsonp-storage-2.txt', queryObj.save, function (err) {
if (err) {
throw err;
} else {
console.log('Saved message successfully.', 'Ready to be read now.');
res.end(queryObj.callback +
'({ fn: "' + queryObj.fn + '", save: ' + queryObj.save + ' })');
}
});
}
Assuming the user types and submits "this is a line of text", the output on the server is a text file called jsonp-storage-2.txt containing this:
{ "text": "this is a line of text" }
After all that, my question is quite simple. How do I prettify the output in the text file?
The code needs work but I'm thinking of using this to try storing larger objects for reading later. However, at the server end, I would like the files (for now) to be easy for me to read when opening them with Notepad, for example.
I have tried using \n and \t like so:
jsonText = '{\n\t"text": "' + origText + '"\n}',
I've also tried \r. But the lines remain unbroken.
Some answers suggest that I can only do this at the level of the encoded string or after the file has been written. Perhaps I missed something simple. Is there a way to do it by manipulating my jsonText variable?
UPDATE:
Just to be clearer about the output desired -- currently the content of the text file produced looks like this:
{ "text": "this is a line of text" }
But I'd like to know if it can be produced like this:
{
"text": "this is a line of text"
}
Use
var os = require('os');
var jsonText = '{' + os.EOL + '\t"text": "' + origText + '"' + os.EOL + '}';
It turns out that when writing a string to a (text) file with Node.js [EDIT: in Windows], use \r\n for a new line.
As with encoded line breaks, both a return carriage and a new line is necessary. So the line of code needed to be this rather than having just \r or just \n:
jsonText = '{\r\n\t"text": "' + origText + '"\r\n}',
The resulting file's content now displays as desired:
{
"text": "this is a line of text"
}

Android WebChromeClient integration with javaScript gives Unexpected Illegal token

Home.java
public void updatePhoto(Bitmap bitmap) {
String bitmapStr = BitMapToString(bitmap);
Home.currentBmp = bitmap;
String parameter = "data:image/jpeg;base64," + bitmapStr;
webView1.loadUrl("javascript:var script = document.createElement('script');" +
"script.type='text/javascript';script.src='form.js';" +
"script.onload=" + "processImage('" + parameter + "');" +
//"script.onload=" + "processImage(':/;//');" +
"document.getElementsByTagName('head').item(0).appendChild(script);");
Log.v(parameter, "QWERTY");
Log.v("QWERTY", parameter);
}
form.js
function processImage(img) {
alert('process image end');
}
this function converts the Bitmap object into a base64 String, then executes an external javascript function (form.js -> processImage(var)). However it doesn't execute processImage and gives an Uncaught SyntaxError: Unexpected token ILLEGAL. However when i uncomment the
//"script.onload=" + "processImage(':/;//');" +
line and comment in
"script.onload=" + "processImage('" + parameter + "');" +
it seems that the function is working well. The possible value for parameter variable would be
data:image/jpeg;base64,iVBORw0KgoAAAANSHUEgAAA......
What I am asking is how am I gonna make the javaScript function work with the parameter? Thanks!

Categories

Resources