Tips and Tricks in a world of Mix


One of the subtle things you might have noticed with the code above is that we are using a <% %> block instead of a <%= %> block when calling Html.RenderPartial().

<%= %> blocks in ASP.NET indicate that a developer wants to render a specified value (for example: <%= "Hello" %> would render "Hello").  <% %> blocks instead indicate that the developer wants to execute code, and that any rendered output within them must be done explicitly (for example: <% Response.Write("Hello") %>.

The reason we are using a <% %> block with our Html.RenderPartial code above is because the Html.RenderPartial() method doesn’t return a string, and instead outputs the content directly to the calling view template’s output stream.  It does this for performance efficiency reasons, and by doing so it avoids the need to create a (potentially very large) temporary string object.  This reduces memory usage and improves overall application throughput.

One common mistake when using Html.RenderPartial() is to forget to add a semi-colon at the end of the call when it is within a <% %> block.  For example, this code will cause a compiler error:

      <% Html.RenderPartial("DinnerForm") %>

You instead need to write:

      <% Html.RenderPartial("DinnerForm"); %>

This is because <% %> blocks are self-contained code statements, and when using C# code statements need to be terminated with a semi-colon.





Leave a Reply

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

You are commenting using your 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

Tag Cloud

%d bloggers like this: