简体   繁体   English

如何将ASP.NET中的xml序列化对象发送到Silverlight

[英]How to send an xml serialized object from ASP.NET to Silverlight

On the button click on an ASP.NET page, I need to load a silverlight application, passing a serialized object from ASP.NET codebehind to MainPage.xaml.cs . 在按钮上单击ASP.NET页面,我需要加载一个silverlight应用程序,将序列化对象从ASP.NET代码隐藏传递到MainPage.xaml.cs How to do this? 这该怎么做?

Why not use WCF? 为什么不使用WCF? This is a perfect fit for sending serialized objects. 这非常适合发送序列化对象。 Also, WCF hosts well on IIS, so it works great with ASP. 此外,WCF在IIS上运行良好,因此它适用于ASP。 Here is a tutorial to get you started. 这是一个帮助您入门的教程 You should be able to see clearly how to define a simply API that you can call from Silverlight. 您应该能够清楚地看到如何定义可以从Silverlight调用的简单API。 You just need to make your object part of a DataContract. 您只需要将对象作为DataContract的一部分。

Some options for you, may help. 一些选项可能会有所帮助。 You could use Javascript - silverlight.net on scripting Silverlight to reach inside the Silverlight object from your page. 你可以使用Javascript - silverlight.net来编写Silverlight脚本 ,从你的页面到达Silverlight对象。

Another option is to have the Silverlight object access the AspNet page to ask for it's xml using PageMethods . 另一个选择是让Silverlight对象访问AspNet页面,使用PageMethods来询问它的xml。 ( System.Web.Services.WebMethod) once it's loaded. (System.Web.Services.WebMethod)一旦加载。

One option is to configure a Silverlight onLoad event in the <object> tag for your app: 一种选择是在应用的<object>标记中配置Silverlight onLoad事件:

<param name="onLoad" value="setInfo" />

Then use script to push the XML into your app (dynamically insert the XML onto the page from ASP.NET): 然后使用脚本将XML推送到您的应用程序中(从ASP.NET动态地将XML插入到页面中):

<script type="text/javascript">
    function setInfo(sender) {
        var msg = '<yourtag>your info here</yourtag>';
        sender.getHost().content.Page.SetInfo(msg);
    }
</script>

To allow script to call your app, configure as follows: 要允许脚本调用您的应用,请配置如下:

public MainPage()
{
    HtmlPage.RegisterScriptableObject("Page", this);
    InitializeComponent();
}

[ScriptableMember]
public void SetInfo(string xml)
{
    // do stuff
}

Register onLoad param in your Silverlight <Object> tag: 在Silverlight <Object>标记中注册onLoad param:

<object data="data:application/x-silverlight-2," type="application/x-silverlight-2">
 <param name="source" value="ClientBin/MySlApp.xap"/>
 <param name="onError" value="onSilverlightError" />
 <param name="background" value="white" />
 <param name="minRuntimeVersion" value="4.0.50826.0" />
 <param name="autoUpgrade" value="true" />
 <param name="onLoad" value="onSilverlightLoad" />
</object>

and register <Script> 并注册<Script>

<script type="text/javascript">
function onSilverlightLoad(sender, args)
{
var mySlControl = sender.getHost();
mySlControl.content.Communicator.MyDeserializer("SerializedObjectString")
}
</script>

In your Silverlight app register `Communicator' object so it is the app itself: 在您的Silverlight应用程序中注册“Communicator”对象,因此它是应用程序本身:

namespace MySilverlightApp
{
        public MySilverlightApp()
        {
            InitializeComponent();
            HtmlPage.RegisterScriptableObject("Communicator", this);
        }
}

and create de-serialization function decorated with [ScriptableMember] : 并创建用[ScriptableMember]修饰的反序列化函数:

[ScriptableMember]
public void MyDeserializer(string _stringPassedFromHtmlDocument)
{
 //deserialize _stringPassedFromHtmlDocument
}

I have above working in one of Sharepoint projects utilising Silverlight webpart. 我上面的一个使用Silverlight webpart的Sharepoint项目。 Serialized object is however rendered into HTML so not sure if that will work for your Button.Click() requirement. 然而,序列化对象被渲染为HTML,因此不确定它是否适用于您的Button.Click()要求。 One thing though should you go down this route: I encountered many many many issues when trying XML serialization and found JSON to be better alternative. 但有一点我应该沿着这条路走下去:在尝试XML序列化时遇到了很多问题,发现JSON是更好的选择。

In your MainPage.xaml.cs, define a property getter/setter for whatever object type you need passed. 在MainPage.xaml.cs中,为需要传递的任何对象类型定义属性getter / setter。

In your ASP.NET page button click handler, set the property to the serialized object. 在ASP.NET页面按钮中单击处理程序,将该属性设置为序列化对象。

If you need this to maintain the serialized object after the page lifecycle finishes, simply change the property setter in MainPage.xaml.cs to persist the serialized object across page lifecycles. 如果您需要在页面生命周期结束后维护序列化对象,只需更改MainPage.xaml.cs中的属性设置器,以便在页面生命周期内保留序列化对象。

Hope this helps. 希望这可以帮助。

Pete 皮特

There are two possible paths here: 这里有两条可能的路径:

1) When the button is pressed, the page posts back to the server, gathers some information, serializes it into XML, shows the silverlight component, which then loads the serialized XML. 1)当按下按钮时,页面回发到服务器,收集一些信息,将其序列化为XML,显示silverlight组件,然后加载序列化的XML。

2) When the page is loaded, the XML data is available. 2)加载页面时,XML数据可用。 Pressing the button simply shows the silverlight component and asks it to load the XML data. 按下按钮只显示silverlight组件并要求它加载XML数据。

Scenario 1 场景1

Here are the steps that you need to take for scenario 1. 以下是您需要针对方案1采取的步骤。

1) Add the silverlight component to the page and embed it in a container (div, table, whatever you like) that is set to runat server. 1)将silverlight组件添加到页面并将其嵌入到设置为runat服务器的容器(div,table,无论你喜欢什么)中。 Note that we also specify an onload param to fire a specific event when the silverlight object has finished loading: 请注意,我们还指定了一个onload参数,以便在silverlight对象完成加载时触发特定事件:

<div id="divDiagram" runat="server">
    <object data="data:application/x-silverlight-2," type="application/x-silverlight-2"
        id="objDiagram">
       <param name="onLoad" value="RefreshDiagram" />
    </object>
</div>

2) In your code-behind, hide this container until the button is pressed. 2)在代码隐藏中,隐藏此容器直到按下按钮。 For example: 例如:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            divDiagram.Visible = false;
        }
    }

    void Button1_Click(object sender, EventArgs e)
    {
        divDiagram.Visible = true;
    }

3) Add a hidden input to hold the serialized data: 3)添加隐藏输入以保存序列化数据:

<input type="hidden" id="txtSerializedData" runat="server" />

4) Set the contents of this input on the button click: 4)在按钮单击上设置此输入的内容:

 txtSerializedData.Value = "some serialized data";

5) Modify the silverlight components code to expose the control to javascript: 5)修改silverlight组件代码以将控件暴露给javascript:

    public MainPage()
    {
        InitializeComponent();

        System.Windows.Browser.HtmlPage.RegisterScriptableObject("DiagramPage", this);
    }

6) Add a method to the silverlight control that can be called from javascript (this is the ScriptableMember attribute) to get the serializable content and work with it: 6)向可以从javascript(这是ScriptableMember属性)调用的silverlight控件添加一个方法,以获取可序列化的内容并使用它:

    [System.Windows.Browser.ScriptableMember()]
    public void RefreshDiagram()
    {
        // Fetch the hidden input control from the page
        var serializedElement = System.Windows.Browser.HtmlPage.Document.GetElementById("txtSerializedData");

        // Then fetch its value attribute
        var sSerializedData = serializedElement.GetAttribute("value");

        // Finally, do something with sSerializedData
    }

7) Finally, add the javascript method to the page that is fired when the silverlight control is loaded: 7)最后,将javascript方法添加到加载silverlight控件时触发的页面:

<script type="text/javascript">

    function GetDiagramPageContent() {
        /// <summary>This method retrieves the diagram page object content</summary>
        // Exceptions are handled by the caller

        var oObject = document.getElementById('objDiagram');

        if (oObject) {
            return oObject.Content;
        } else {
            return null;
        }
    }

function RefreshDiagram() {
    try {
        var oContent = GetDiagramPageContent();
        try {
            // If we don't have content or a diagram page, bail
            if ((oContent == null) || (oContent.DiagramPage == null)) {
                return;
            }
        } catch (ex) {
            return;
        }

         // Now ask the control to refresh the diagram
        oContent.DiagramPage.RefreshDiagram();
    } catch (ex) {
        alert('Javascript Error (RefreshDiagram)\r' + ex.message);
    }
}
</script>

Scenario 2 情景2

Scenario 2 is very similar to scenario 1, with the following changes: 场景2与场景1非常相似,但有以下更改:

1) Do not include the onLoad param in the silverlight object. 1)不要在silverlight对象中包含onLoad参数。 Instead, call the RefreshDiagram javascript method from the client-side button click. 而是从客户端按钮单击调用RefreshDiagram javascript方法。

2) Do not show or hide the containing div in code-behind. 2)不要在代码隐藏中显示或隐藏包含div。 Instead, use the style attributes to control the visibility: 而是使用样式属性来控制可见性:

<div id="divDiagram" runat="server" style="visibility: hidden; visibility: visible">

and in the javascript button click event: 并在javascript按钮单击事件:

var oDiv = document.getElementById("divDiagram");
oDiv.style.visibility = "";
oDiv.style.display = "";

3) Load the hidden text box in pageload instead of on the server-side button click. 3)在页面加载中加载隐藏文本框,而不是在服务器端按钮单击。

This might help 这可能有所帮助

Passing Objects between ASP.NET ans Silverlight Controls 在ASP.NET和Silverlight控件之间传递对象

best regards 最好的祝福

您可以使用Mike Talbot称为SilverlightSerializer的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM