using Silverlight 4 in an ASP.NET MVC 3 application and accessing data with JSON
2012-05-10 22:48
841 查看
Posted on April 11th, 2011
ASP.NET MVC is such a great platform for web applications because it makes it so easy to tackle many different integration challenges. You need to add a Silverlight application to your web site and send it some JSON data to work with? No sweat. Stumped on where to start? Well, you are in the right place. Let's make it happen.
In honor of Mix 11 kicking off tomorrow, we will imagine that we are tasked with the need to build a web application that renders a list of MIX 11 sessions and allows the video of each session to be viewed in a browser (of course we don't really need to build such a solution because the live.visitmix.com site already provides that content for us...but, for the sake of being hypothetical). What a perfect reason to use Silverlight in a MVC 3 web application! We will work through rendering a Silverlight application in an MVC 3 view and populate it with a list of MIX 11 session names delivered in JSON from our MVC application. We will not be addressing how to render video in Silverlight in this post though, so if you want to take the Silverlight portion further you may want to check out www.iwantmysilverlight.com (is anyone actually rockin' that domain name?).
As always, we begin with a blank ASP.NET MVC 3 Web Application project (named Website) using an Empty project template and target the Razor view engine. Once the solution is created with the MVC project we will add a new Silverlight Application project to the solution.
To start this post I didn't have the Silverlight Developer Tools installed on my workstation running Visual Studio 2010 (Service Pack 1), so I encountered the following dialog upon clicking OK from the add project dialog:
Clicking on the link in this dialog opened up a browser and downloaded the installer. After running the installer, restarting Visual Studio 2010, and attempting to add the new Silverlight Application project a second time I found success. The Silverlight Application project prompts you with an options dialog:
I unchecked the options for "Add a test page that references the application" and "Enable Silverlight debugging (disables javascript debugging)" and clicked OK. Once the Silverlight Application project was added my solution tree looked like so:
With the projects in place we are ready to start adding some code. First up, we need to add a controller and a view that will render a page with our Silverlight application on it. Lets add a good old
Our
If we do a quick F5 to check out our page we are presented with the following dialog:
I clicked No...nothing broke or melted. The page showed up with our h1 tag screaming at us in huge bold font. Now lets see about getting our Silverlight in that view. The SilverlightApplication project comes pre-loaded with a
The default content for the
We will drag and drop a
Our
We can preview this by right clicking on the SilverlightApplication project in the Solution Explorer and selecting "View in Browser" (or hitting Ctrl+Shift+W). With our browser open we can see our Silverlight running, displaying the "Session Videos" text. If we right click on the window content we get the "Silverlight" context menu:
Now lets get this puppy running in our view. Guess what! By adding the SilverlightApplication to our solution after we added the ASP.NET MVC 3 Web Application we were presented with the "Host the Silverlight application in a new or existing Web site in the solution" option pre-checked and our project named Website pre-selected in the drop down. Since we left that option checked and the Website project selected, when we did a build of ourWebsite application (the F5 we did earlier to preview it) the
We can add an
If we do another F5 we will see our page with our Silverlight application included.
So we have some Silverlight running in an ASP.NET MVC 3 web application. Coolio! Now lets see what we can do to populate some data in that Silverlight. We will create a new action method in our
We also need to add a route to our route table to be able to call this action method. An update to our
Our MVC application is set up to provide data for our Silverlight application to consume. Our final step involves adding the code to our Silverlight application to hit our MVC route and process the data returned. To keep it simple, we will modify our
This will ensure that the rendering of our
Lets take a look at the code in the file as a whole and then we will go over the parts.
In the
In our
If we go back to our MVC project and do an F5 we will see our Silverlight application rendered in our page and populated with the JSON data from our
And voilà, we have a starting point for an integration between ASP.NET MVC 3 and a Silverlight 4 application. The rest is easy right? Simply build a robust Silverlight application solution and update the MVC application to return more complex JSON data. Knock that out in a day or two? I think I'll spend the next day or two sitting at home watching the Mix 11 session online and toss some sadfaces out as I watch all the Twitter chatter from all of those out in Vegas having fun instead. Oh, and answer reader comments of course!
ASP.NET MVC is such a great platform for web applications because it makes it so easy to tackle many different integration challenges. You need to add a Silverlight application to your web site and send it some JSON data to work with? No sweat. Stumped on where to start? Well, you are in the right place. Let's make it happen.
In honor of Mix 11 kicking off tomorrow, we will imagine that we are tasked with the need to build a web application that renders a list of MIX 11 sessions and allows the video of each session to be viewed in a browser (of course we don't really need to build such a solution because the live.visitmix.com site already provides that content for us...but, for the sake of being hypothetical). What a perfect reason to use Silverlight in a MVC 3 web application! We will work through rendering a Silverlight application in an MVC 3 view and populate it with a list of MIX 11 session names delivered in JSON from our MVC application. We will not be addressing how to render video in Silverlight in this post though, so if you want to take the Silverlight portion further you may want to check out www.iwantmysilverlight.com (is anyone actually rockin' that domain name?).
As always, we begin with a blank ASP.NET MVC 3 Web Application project (named Website) using an Empty project template and target the Razor view engine. Once the solution is created with the MVC project we will add a new Silverlight Application project to the solution.
To start this post I didn't have the Silverlight Developer Tools installed on my workstation running Visual Studio 2010 (Service Pack 1), so I encountered the following dialog upon clicking OK from the add project dialog:
Clicking on the link in this dialog opened up a browser and downloaded the installer. After running the installer, restarting Visual Studio 2010, and attempting to add the new Silverlight Application project a second time I found success. The Silverlight Application project prompts you with an options dialog:
I unchecked the options for "Add a test page that references the application" and "Enable Silverlight debugging (disables javascript debugging)" and clicked OK. Once the Silverlight Application project was added my solution tree looked like so:
With the projects in place we are ready to start adding some code. First up, we need to add a controller and a view that will render a page with our Silverlight application on it. Lets add a good old
HomeControllerwith a
Indexaction method. Our
HomeController.csfile will contain:
usingSystem.Web.Mvc; namespaceWebsite.Controllers { publicclassHomeController:Controller { publicActionResultIndex() { returnView(); } } }
Our
Views/Home/Index.cshtmlfile will contain:
@{ ViewBag.Title="Index"; } <h1>OurSilverlight application demo</h1>
If we do a quick F5 to check out our page we are presented with the following dialog:
I clicked No...nothing broke or melted. The page showed up with our h1 tag screaming at us in huge bold font. Now lets see about getting our Silverlight in that view. The SilverlightApplication project comes pre-loaded with a
MainPage.xamlfile. If we open that file in Visual Studio 2010 it will give us a split window with a Design view at the top and a XAML view at the bottom. From here we can use the Toolbox window to add some UX stuff. If you don't have this displayed because you build rad ASP.NET MVC web applications without that crazy design view stuff or you recently read Scott Hanselman's blog post on how to Simplify your Visual Studio 2010 Toolbar and Free Your Mind and turned off everything under the sun then you can get it back by hitting Ctrl+Alt+X or navigating to View -> Toolbox from the main menu.
The default content for the
MainPage.xamlfile looks like:
<UserControlx:Class="SilverlightApplication.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignHeight="300"d:DesignWidth="400"> <Gridx:Name="LayoutRoot"Background="White"> </Grid> </UserControl>
We will drag and drop a
TextBlockand set the
Textattribute to "Session Videos". This will add the following XAML tag to the
<Grid>tag:
<TextBlockHeight="23"HorizontalAlignment="Left"Margin="12,12,0,0" Name="textBlock1"Text="Session Videos"VerticalAlignment="Top"/>
Our
MainPage.xamlfile will end up looking like so:
<UserControlx:Class="SilverlightApplication.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"d:DesignWidth="400">
<Gridx:Name="LayoutRoot"Background="White">
<TextBlockHeight="23"HorizontalAlignment="Left"Margin="12,12,0,0" Name="textBlock1"Text="Session Videos"VerticalAlignment="Top"/></Grid>
</UserControl>
We can preview this by right clicking on the SilverlightApplication project in the Solution Explorer and selecting "View in Browser" (or hitting Ctrl+Shift+W). With our browser open we can see our Silverlight running, displaying the "Session Videos" text. If we right click on the window content we get the "Silverlight" context menu:
Now lets get this puppy running in our view. Guess what! By adding the SilverlightApplication to our solution after we added the ASP.NET MVC 3 Web Application we were presented with the "Host the Silverlight application in a new or existing Web site in the solution" option pre-checked and our project named Website pre-selected in the drop down. Since we left that option checked and the Website project selected, when we did a build of ourWebsite application (the F5 we did earlier to preview it) the
SilverlightApplication.xapfile was created and deployed to a
ClientBindirectory in our MVC project.
We can add an
<object>tag to our
Index.cshtmlview file to render our Silverlight application within the view. The code for our view file will be:
@{ ViewBag.Title="Index"; } <h1>OurSilverlight application demo</h1><object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="400" height="300">
<param name="source" value="ClientBin/SilverlightApplication.xap"/>
<param name="background" value="red" />
<param name="minRuntimeVersion" value="4.0.60129.0" />
<param name="autoUpgrade" value="true" />
<a href="http://www.microsoft.com/getsilverlight/get-started/install/" style="text-decoration:none">
<img src="http://go.microsoft.com/fwlink/?LinkId=161376"
alt="Get Microsoft Silverlight" style="border-style:none"/>
</a>
</object>
If we do another F5 we will see our page with our Silverlight application included.
So we have some Silverlight running in an ASP.NET MVC 3 web application. Coolio! Now lets see what we can do to populate some data in that Silverlight. We will create a new action method in our
HomeController.csfile named
SessionVideoListthat will return a
JsonResultthat will contain a list of session names we can use in our Silverlight application. We can create a
List<string>of some session names and return it as a
Jsonobject. Our updated controller code:
usingSystem.Collections.Generic; usingSystem.Web.Mvc; namespaceWebsite.Controllers { publicclassHomeController:Controller { publicActionResultIndex() { returnView(); } publicJsonResultSessionVideoList() { var sessionVideos =newList<string>{"Keynote","Silverlight Boot Camp", "Fun with ASP.NET MVC 3 and MEF","ASP.NET MVC 3 @:The Time is Now"}; returnJson(sessionVideos,JsonRequestBehavior.AllowGet); } } }
We also need to add a route to our route table to be able to call this action method. An update to our
Global.asax.csfile will look like so:
usingSystem.Web.Mvc; usingSystem.Web.Routing; namespaceWebsite { publicclassMvcApplication:System.Web.HttpApplication { publicstaticvoidRegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(newHandleErrorAttribute()); } publicstaticvoidRegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "SessionVideoList", "SessionVideoList", new{ controller ="Home", action ="SessionVideoList"} ); routes.MapRoute( "Default", "{controller}/{action}/{id}", new{ controller ="Home", action ="Index", id =UrlParameter.Optional} ); } protectedvoid Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } } }
Our MVC application is set up to provide data for our Silverlight application to consume. Our final step involves adding the code to our Silverlight application to hit our MVC route and process the data returned. To keep it simple, we will modify our
MainPage.xamlfile to enlarge the TextBlock element so that it fills the Silverlight application and use that to render our list of session names. We can add a
Widthattribute and change the existing
Heightattribute on our
<TextBlock>tag:
<TextBlockHeight="276"HorizontalAlignment="Left"Margin="12,12,0,0" Name="textBlock1"Text="Session Videos"VerticalAlignment="Top"Width="376"/>
This will ensure that the rendering of our
TextBlockwill be big enough to display a handful of lines of text. From here we need to open up our
MainPage.xaml.csfile and add some code to call our MVC action url and process the response stream content. In the constructor for
MainPagewe will add an instantiation of a
Uriobject, a
WebClientobject, and do an async read of the
Uriobject with the
WebClientobject. We will also add a private method named
openReadCompletedthat we will add to the
WebClient.OpenReadCompletedevent handler. This method will handle processing the JSON data from the response stream and populating our
TextBlockelement. We are going to use
System.Jsonto process the JSON data which requires us to add a reference to the .NET assembly in our SilverlightApplication project.
Lets take a look at the code in the file as a whole and then we will go over the parts.
usingSystem; usingSystem.Json; usingSystem.Net; namespaceSilverlightApplication { public partial classMainPage { publicMainPage() { InitializeComponent(); var serviceUri =newUri("/SessionVideoList",UriKind.Relative); var webClient =newWebClient(); webClient.OpenReadCompleted+= openReadCompleted; webClient.OpenReadAsync(serviceUri); } privatevoid openReadCompleted(object sender,OpenReadCompletedEventArgs e) { if(e.Error!=null)return; var sessions =(JsonArray)JsonValue.Load(e.Result); foreach(string sessionName in sessions) { this.textBlock1.Text+=string.Format("{0}{1}",Environment.NewLine, sessionName); } } } }
In the
MainPageconstructor we instantiate a new
Uriobject. We pass in a relative uri string that represents the route to our action method. We need to include the
UriKindargument (value of
UriKind.Relative) in this constructor in order for our Silverlight application to correctly resolve the path when rendered in our MVC application. Then we instantiate our
WebClient, add the event handler, and do our asynchronous read.
publicMainPage() { InitializeComponent(); var serviceUri =newUri("/SessionVideoList",UriKind.Relative); var webClient =newWebClient(); webClient.OpenReadCompleted+= openReadCompleted; webClient.OpenReadAsync(serviceUri); }
In our
openReadCompletedmethod we do a simple check for errors and return without taking any action if we encounter an error. From there we use the
JsonValue.Loadmethod to deserialize the response stream data that is stored in the
OpenReadCompletedEventArgs.Resultproperty and cast it to a
JsonArrayobject. This is based on knowing the structure of the JSON objects we are dealing with...there are other JSON object types that can be used here. More info can be found on MSDN. Finally, we iterate through the
JsonArrayobject and add the session name to a new line in our TextBlock element.
privatevoid openReadCompleted(object sender,OpenReadCompletedEventArgs e) { if(e.Error!=null)return; var sessions =(JsonArray)JsonValue.Load(e.Result); foreach(string sessionName in sessions) { this.textBlock1.Text+=string.Format("{0}{1}",Environment.NewLine, sessionName); } }
If we go back to our MVC project and do an F5 we will see our Silverlight application rendered in our page and populated with the JSON data from our
SessionVideoListaction method.
And voilà, we have a starting point for an integration between ASP.NET MVC 3 and a Silverlight 4 application. The rest is easy right? Simply build a robust Silverlight application solution and update the MVC application to return more complex JSON data. Knock that out in a day or two? I think I'll spend the next day or two sitting at home watching the Mix 11 session online and toss some sadfaces out as I watch all the Twitter chatter from all of those out in Vegas having fun instead. Oh, and answer reader comments of course!
相关文章推荐
- Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application
- [转]Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application (3 of 10)
- Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application (9 of 10)
- MVC architecture in ASP.Net using C# and Microsoft Data Access Application block
- EF Database First with ASP.NET MVC: Creating the Web Application and Data Models开发遇到问题的解决办法
- http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
- [翻译]Accessing and Updating Data in ASP.NET 2.0: Examining the Data Source Control's Events
- Redirect and Post JSON object in ASP.NET MVC
- Integrating OpenID in an ASP.NET MVC Application using DotNetOpenAuth
- ASP.NET MVC – Create easy REST API with JSON and XML(转)
- Create a more Complex Data Model for an Asp.Net MVC Application
- Working with Data in ASP.NET 2.0 :: Master Pages and Site Navigation
- Active Directory Authentication in ASP.NET MVC 5 with Forms Authentication and Group-Based Authorization
- Displaying a Sorted, Paged, and Filtered Grid of Data in ASP.NET MVC
- Asp.net MVC 4 application with Flexigrid, jQuery UI, and jQuery validation
- jQuery UI Accordion in ASP.NET MVC - feed with data from database
- Plug-In Hybrids: ASP.NET WebForms and ASP.MVC and ASP.NET Dynamic Data Side By Side
- ASP.NET MVC #01, Create a Movie Database Application in 15 Minutes with ASP.NET MVC
- Upload files in ASP.NET MVC with JavaScript and C#
- ASP.NET MVC - Redirect-and-Post-JSON-Object-in-ASP-NET-MVC