Spark View Engine – Render Partial While Passing the Model

Saturday, February 13, 2010

Just a quick follow up on my previous post specifically about rendering partial views using the Spark View Engine.  If you want to use a partial view and you also want to pass it a model, you just create parameter and pass the model in that parameter.


As I stated, the convention for the shared content is to create a file in the “Shared” view directory and prefix the file with the “_”.


For example:

I have created a post list partial file and I am going to call it from my “Index” view in the “Home” folder.



In the HomeController class, the Index action is just returning 10 items in a IList collection.


   1: public ActionResult Index()
   2: {
   3:     IList<PostDto> items = _postService.GetMostRecentPosts();
   5:     ViewData["BasicPosts"] = items;
   6:     return View();
   7: }

Next, my Index view passes the collection of posts to the partial control.  The Index.spark file has the following code.

   1: <viewdata BasicPosts="IList<PostDto>">
   4: <postList posts="BasicPosts" />



Now the model is in the partial file and I can do with it what ever I want. In this example, the _postList.spark file has the following code that loops through the collection of posts and displays the “Title”.

   1: <ul>
   2: <for each="var post in posts">
   3:     <li>${post.Title}</li>
   4: </for>
   5: </ul>



The above sample produces this partial view.


comments powered by Disqus