Search

Custom Search
Showing posts with label Client Side Programming. Show all posts
Showing posts with label Client Side Programming. Show all posts

Tuesday, March 18, 2008

using JSON in C#.Net

I never thought that my objects can be accessed in javascript until I discover JSON. JSON or Javascript Object Notation is a simple data transformation from your serverside objects to clientside scripting.
A string like
'person = {"firstName": "Brett", "lastName":"McLaughlin", "email":
"brett@newInstance.com" } '

can be deserialized into JSON object using eval. Then can be accessed as simple as person.firstName. Below is a sample javascript code:

var myJSON = 'person = {"firstName": "Brett", "lastName":"McLaughlin",
"email": "brett@newInstance.com" } ' ;
eval(myJSON);
alert(person.firsName + ' ' + person.lastName + ', ' + person.email);

the code above will give a pop-up message saying:
Brett McLaughlin, brett@newInstance.com

Now how can we create a JSON object in C#.net and be able to pass it on clientside? Here is the procedure:

1. Create a struct to be serialized as JSON:

public struct person
{
public string firstName;
public string lastName;
public string email;
}

2. Create a method that will return a serialized JSON object

public string SerializedJSON(object toSerialize, string className)
{
System.Web.Script.Serialization.JavaScriptSerializer jss;
jss = new System.Web.Script.Serialization.JavaScriptSerializer();
objectSystem.Text.StringBuilder sbControls = new
System.Text.StringBuilder();
jss.Serialize(toSerialize, sbControls);
return className + "=" + sbControls.ToString();
}

3. then register the clientside method to call with parameter as JSON serialized string. This may be an attributes of controls event or a a method call on clientside

//as attribute
string serialized = SerializedJSON(person, "person");
button1.Attributes.add("onClick",
"parseJSON('"+ serialized +"')");
//as method call on serverside

ScriptManager.RegisterClientScriptBlock(this,this.GetType(),
"JS
Method Call","parseJSON('"+ serialized +"')", true);

4. Now with those server side code, here is how we do the clientside:

function parseJSON(serializedJSON)
{
eval(serializedJSON);
alert(person.firsName + ' ' + person.lastName + ', ' +
person.email);
}

You can even use JSON on array of objects and be able to call it by index on clientside like

person[0].firstName;
or
person[1].firstName;

I usually use list<object> then serialize it to JSON. And there are many things to explore on JSON and that is what I'm doing right now! Thanks JSON!

links: http://www-128.ibm.com/developerworks/web/library/wa-ajaxintro10/

Tuesday, March 11, 2008

Adding Javascript file programmatically in C#

Just got it from ASP.Net Forum and found it very useful for me. Thanks to NC01!!

string resourceName = "YourJavaScriptFile.js";
if ( !this.Page.IsClientScriptBlockRegistered(resourceName) )
{
// If the file is on the server root:
// Ex:
http://localhost/YourJavaScriptFile.js
string filePath = System.Web.HttpContext.Current.Request.Url. GetLeftPart( UriPartial.Authority) + "\\" + resourceName;
// If the file is on the app virtual root:
// Ex: C:/Inetpub/wwwroot/Test/YourJavaScriptFile.js
string filePath = System.AppDomain.CurrentDomain.BaseDirectory + resourceName;
// If the file is in a sub-folder inside of the app virtual root:
// Ex: C:/Inetpub/wwwroot/Test/ScriptFiles/YourJavaScriptFile.js
string filePath = System.AppDomain.CurrentDomain.BaseDirectory + "ScriptFiles/" + resourceName;
string scriptText = string.Format( System.Globalization.CultureInfo.InvariantCulture, "\n<script type='text/JavaScript' src='{0}'></script>\n", filePath);
this.Page.RegisterClientScriptBlock(resourceName, scriptText);
}

Note that RegisterOnSubmitStatement, RegisterStartupScript, RegisterClientScriptBlock, etc have changed since version 1.1 and you will get a compiler warning with the above. See http://msdn2.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.aspx for more info.

I just highlighted the property of getting the BaseURL, System.AppDomain.CurrentDomain.BaseDirectory , i've been looking for it before and finally I got an answer. What I do before is put my baseURL in web.Config, but everytime I deploy it on different test site I have to change the value on web.config before publishing.

Saturday, March 8, 2008

Calling Server Side Method with postback in C#

I've been researching for how to call server side methods over the internet but has been frustrated for all I searched was calling server side method without postback using pagemethods or using the ICallBackEventHandler that works like webservice calls in AJAX. I've been pondering time to solve this and found a solutions for myself.

Here is how I did it:
  • Create a linkbutton on design and write an event for this. This event will be called on client side by some javascript function.
  • Register the Server Side Function by using the following:
StringBuilder jscript = new StringBuilder();
jsscript.append("function callServerEvent(){");
jsscript.append(ClientScript.GetPostBackEventReference (LinkButton1, "") + ";}");
RegisterClientScriptBlock("call server", jsscript.ToString());

  • Do this on Page_Load event, then you can now call callServerEvent() from javascript will do a post back and update controls.
  • To hide the control on rendering the page set the display:none on LinkButon's style.
I usually use this in calling server
side function to update controls inside my updatepanel. Using Pagemethods are used for calling static methods and using ICallBackEventHandler is for calling serverside method but with no postback at all.

Friday, March 7, 2008

Opening a new window without toolbars in C#

Here is window.open syntax:

winRef = window.open( URL, name [ , features [, replace ] ] )

The parameters URL, name, features, replace have the following meaning:

URL
String specifying the location of the Web page to be displayed in the new window. If you do not want to specify the location, pass an empty string as the URL (this may be the case when you are going to write some script-generated content to your new window).

name
String specifying the name of the new window. This name can be used in the same constructions as the frame name provided in the frame tag within a frameset .

features
An optional string parameter specifying the features of the new window. The features string may contain one or more feature=value pairs separated by commas.

replace
An optional boolean parameter. If true, the new location will replace the current page in the browser's navigation history. Note that some browsers will simply ignore this parameter.

The following features are available in most browsers:
toolbar=0/1
-Specifies whether to display the toolbar in the new window.
location=0/1
-Specifies whether to display the address line in the new window.
directories=0/1
-Specifies whether to display the Netscape directory buttons.
status=0/1
-Specifies whether to display the browser status bar.
menubar=0/1
-Specifies whether to display the browser menu bar.
scrollbars=0/1
-Specifies whether the new window should have scrollbars.
resizable=0/1
-Specifies whether the new window is resizable.
width=pixels
-Specifies the width of the new window.
height=pixels
-Specifies the height of the new window.
top=pixels
-Specifies the Y coordinate of the top left corner of the new window. (Not supported in version 3 browsers.)
left=pixels
-Specifies the X coordinate of the top left corner of the new window. (Not supported in version 3 browsers.)


Calling the window.open on serverside:

RegisterClientScriptBlock("Open Window","<script> window.open('sample.aspx','sample','toolbar=No, width=300, height=190, resizable=No, top=400, left=600')</script>");

To Create a page on the fly:

StringBuilder jscript = new StringBuilder();
jscript.append("<script>");
jscript.append("win=window.open('','login',");
jscript.append("'toolbar=No, width=300, height=190, resizable=No, top=400, left=600');");
jscript.append("win.response.write('<BODY>');");
jscript.append("win.response.write('this page is created on the fly!');");
jscript.append("win.response.write('</BODY>');");
jscript.append("</script>");
RegisterClientScriptBlock("Open Window", jsscript.ToString());


reference: http://www.javascripter.net/faq/openinga.htm

Adsense Banner