InitParams in Silverlight – passed via MVC

The old skool way of passing InitParams in aspx is well documented, adding a:

<param name="initParams" value="<%=InitParams%>" />

which is accessing the public ‘InitParams’ member in the code-behind file, which is inevitably set up via the ‘Page_Init’ handler.

All well and good, but not practical in MVC, so… how to do this?

(NB. This is just how I’ve done it, it’s not the only solution)

There are a few things to change:

1. The Model

I’ve created a SilverlightHostModel, it only has one property in it (at the moment), to hold the InitParams:

namespace Webby.Models
{
    public class SilverlightHostModel
    {
        public string InitParams { get; set; }
    }
}

2. The Controller

The controller is going to create the model and pass it to the view..

public ViewResult Ria()
{
    SilverlightHostModel host = new SilverlightHostModel();
    host.InitParams = "IpAddress=" + System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

    return View(host);
}

3. The View

The view needs to be strongly-typed to the Model, so we add this to the top of the new view:

@model Webby.Models.SilverlightHostModel

and where we’re hosting the Silverlight control itself, we change the param to read:

<param name="initParams" value="@Model.InitParams"/>

4. The App.xaml.cs Application_Startup

You (I presume) already have this done, but you would get your new parameter like so

private void Application_Startup(object sender, StartupEvents e)
{
    //Get the ip address from InitParams
    string ip = e.InitParams["IpAddress"];

    this.RootVisual = new MainPage();
}

Done!

Print | posted @ Friday, January 6, 2012 12:40 AM

Comments on this entry:

No comments posted yet.

Post A Comment
Title:
Name:
Email:
Comment:
Verification: