Tuesday 12 June 2012

How To Access Silverlight function using javascipt - sharepoint

Create  a   silverlight  application  as  follows

using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Net;
using  System.Windows;
using  System.Windows.Controls;
using  System.Windows.Documents;
using  System.Windows.Input;
using  System.Windows.Media;
using  System.Windows.Media.Animation;
using  System.Windows.Shapes;

namespace sljsinterop
{
[ScriptableType]
public partial classMainPage : UserControl
{
public MainPage()
{
InitializeComponent();
HtmlPage.RegisterScriptableObject("Page", this);
}
[ScriptableMember]
publicvoid fn(string s)
{
MessageBox.Show(s);
}
}
}
}

The [ScriptableType] attribute  over the class and the [ScriptableMember] over the function provides access for  javascript to invoke  the function.

Now  Build  the  solution and keep  the  .Xap  file  seperately.

First  Create  New Project in  Visual Studio



Then  in  the Project  templates  select   Sharepoint  2010  --->  Empty Project



Select  the  site that  you  want   to deploy  the  web  part  to.



Then  in the  solution explorer  right  click on the project file  and  click add --->New Item

                   



Then in the item template  choose  Sharepoint 2010  ---->   visual webpart template



Now  open  the   design page  of  the  Visual  Webpart




Now  paste   the  xap   file  that  we   created   into   the project  and  include it in the visual  webpart  using  the <Object>  tag.

<objectid="sl1"data="data:application/x-silverlight-2,"type="application/x-silverlight-2"width="600"height ="600">
 <param name="source"value="sljsinterop.xap"/>
 <paramname="onError"value="onSilverlightError"/>
 <paramname="background"value="white"/>
 <paramname="minRuntimeVersion"value="4.0.50826.0"/>
 <paramname="autoUpgrade"value="true"/>
</object>



I have given ID for the object tag as "sl1".Now in Javascript  we are going to create an object of sl1 and use it to call function from silverlight.

The  below  javascript  code  can be present inside the visualwebpart  or  in the page where the webpart is used,you can also use this inside a content editor.

<script language="javascript" type="text/javascript">
function Button1_onclick() {
var sl = document.getElementById("sl1");
sl.focus();
sl.Content.Page.fn("invoked from javascript");
}
 </script>

No comments:

Post a Comment