Hugoware

The product of a web developer with a little too much caffeine

Render Partial — But With Arguments!

with 6 comments

One thing that I haven’t really liked about MVC was using RenderPartial instead of an actual UserControl. Its not that you can’t use them but that there is a disconnect between the control state and the render phase which makes it pretty much impossible to really work with them inline.

I say ‘pretty much’ because I’ve done a lot of work to let people use WebControls inline with MVC code.

Using the existing RenderPartial requires that you pass in the name of the UserControl that you want to render. You can also provide an object argument that is passed in as the ‘Model’ for the partial view. The UserControl can access the passed in object via the ‘Model’ property — even cast it into the correct type directly.

Personally, I use a lot of Models in my projects now. I used to suggest that you pass around objects using a wrapper for anonymous types but I’ve found that if you plan to move it from a Controller to a View or from a View to a UserControl then you ought to define a class.

Using RenderPartial Without Really Using It

So instead of calling RenderPartial directly, what about using the Model that we have in place to make the call for us. Not only that, we can even define our class to accept arguments directly. Here is an example of a simple dialog box…

using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MvcTest.Models {

    //simple dialog box example
    public class DialogBox {

        //rendering the dialog box
        public static void Render(ViewPage insideView, string title, string message) {
            insideView.Html.RenderPartial(
                "DialogBox",
                new DialogBox() {
                    Title = title,
                    Message = message
                });
        }

        //Properties
        public string Title { get; set; }
        public string Message { get; set; }

    }

}

Then we could simply use our code inline by calling the DialogBox.Render instead of the RenderPartial method.

<% DialogBox.Render(this, "My Title", "This is the message to display."); %>

You could also use an approach like this to make creating UserControl templates easier.

using System;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MvcTest.Models {

    //simple product list example
    public class ProductListing {

        //rendering the list of controls
        public static void Render(ViewPage insideView, List<Product>, Action<Product> renderRow) {
            insideView.Html.RenderPartial(
                "ProductListing",
                new DialogBox() {
                    AllProducts = products,
                    RenderRow = renderRow
                });
        }

        //Properties
        public List<Product> AllProducts { get; set; }
        public Action<Product> RenderRow { get; set; }

    }

}

And then you could call your method inline and provide the template action.

[View.aspx]

<!-- snip -->
<% DialogBox.Render(
         this,
         products,
         (item) => { %><li><% =item.Name %></li><% }
         ); %>
<!-- snip -->

[UserControl.ascx]

<%@ Control Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<MvcTest.Models.ProductListing>" %>

<h3>Featured Products</h3>
<ul>
<% 
    foreach (Product item in this.Model.AllProducts) {
        this.Model.RenderRow(item);
    } 
%>
</ul>

The above example is probably over simplified but you probably get the idea. This may not be a big gain, but if you plan to use the same UserControl often, then this might help simplify the call.

Advertisements

Written by hugoware

October 26, 2009 at 11:38 pm

6 Responses

Subscribe to comments with RSS.

  1. I’ve been meaning to ask you about MVC vs WebForm’s using pagemethods and / or web services. This year I’ve evolved – I’m being kind because I really don’t know what I’m doing – sort of a hybrid approach with heavy client side rendering with jQuery and PageMethods. In short, I’m sick of the PostBack cycle. Many times I gather my data server side, pump hmtl or json to the client and manipulate everything more easily with jQuery. Most times I collect my updates in a hidden form, postback, parse, and save.

    That said, is MVC worth a look? Are you trading PostBack complexity for other complexity? Being a pattern guy I’m ok with goals of MVC, but are there other complexities that arise as a by product?

    ActiveEngine Sensei

    October 27, 2009 at 6:42 am

    • Personally, I think MVC is worth a look — but realize it is a different approach to the same problem. WebForms are getting a major overhaul in this next release of ASP.NET so you will have more control over your output than you do now.

      It is true that you lose some of the built in functionality of ASP.NET when you move to MVC — the ViewState, as ugly as it is, does have advantages that are lost. Additionally, the PostBack model makes UI programming easier than with MVC (Templates, encapsulated logic for controls)

      However, all that said I still think that I churn out applications faster with MVC than WebForms. With the Controller/Action approach you can break apart an application into “what” it does and create actions for each of the “steps” to do it.

      So you might have a controller like…



      public class FileController : Controller {

      public ActionResult Rename(int? fileId, string newName) {
      ...
      }

      public ActionResult Delete(int? fileId) {
      ...
      }

      public ActionResult Download(int? fileId, FileFormat? format) {
      ...
      }

      }

      Instead of having hard coded ‘Button’ PostBacks to functionality, you just simply have routes with functionality. It doesn’t matter who calls it, or where it is called from — if you make the request and have the correct arguments then the job gets done.

      The nice thing is that you can use the EXACT same approach for any data type (JSON, XML, Text, Images, etc) — which makes programming for the client side much MUCH easier. PageMethods have always been a little … awkward to say the least, but Controller Actions linked into jQuery.ajax is simple and easy.

      MVC and WebForms each addresses a different approach to web development. WebForms focuses on faster development and less control.

      MVC gives more control over the entire experience (from UI to returned content) but you might find yourself missing some WebForm functionality from time to time (and it might slow you down some)

      Anyways… that was the long answer…

      Short answer – yeah, you might check it out since you like client side development 🙂

      webdev_hb

      October 27, 2009 at 8:39 am

  2. I know every time someone posts something using the WFVE the “sparkplugs” show up and extol the wonderfulness which is Spark, so sorry to be that guy, but you should really use Spark if you’re going through all this work. Spark macros make what you want to do much cleaner and more intuitive.

    John Sheehan

    October 27, 2009 at 1:19 pm

    • I read over some stuff about Spark and it looked to me a lot like XSLT (I think thats what it was…) — I really can’t speak for it since I haven’t used it though…

      Maybe I’ll make some time for it this weekend.

      webdev_hb

      October 27, 2009 at 1:47 pm

  3. From a comment I just received on StackOverflow, a guy has created a C# solution that emits jQuery! This dude’s presentation is here. It looks as though you can issue:

    var div = new jQuery(“”)
    .text(“Some text”)
    .show();

    and the Lexer – parser will emit the corresponding Javascript. Check it out

    ActiveEngine Sensei

    October 29, 2009 at 6:50 am

    • Wow — interesting and wild all at the same time — who would have thought of doing something like that?

      webdev_hb

      October 29, 2009 at 2:43 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: