Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you use a runat="server" tag on ANY element, such as a DIV it will render that code as a separate <strong>method</strong> in the compiled page.</p> <p>If you're converting 'legacy' code its a good idea to remove all runat tags right up front otherwise you end up in a situation where code like the following gives you an error.</p> <pre><code>&lt;% foreach (var cat in cats) { %&gt; &lt;div runat="server"&gt; &lt;span class="name"&gt; &lt;%= cat.name %&gt; &lt;/span&gt; is a &lt;span class="breed"&gt; &lt;%= cat.breed %&gt; &lt;/span&gt; &lt;/div&gt; &lt;% } %&gt; </code></pre> <p>This code will fail telling you some craziness about <code>'cat'</code> being out of scope. Eventually when you look at the full generated code you'll see that the <code>&lt;div&gt;</code> has been generated as its whole own method - which is of course a different scope with no cats in sight.</p> <p>Back for a second to the default template for an MVC application:</p> <p>You'll see the current template gives you this for the <code>head</code> :</p> <pre><code>&lt;head runat="server"&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt; &lt;title&gt;&lt;%= Html.Encode(ViewData["Title"]) %&gt;&lt;/title&gt; &lt;link href="../../Content/Site.css" rel="stylesheet" type="text/css" /&gt; &lt;/head&gt; </code></pre> <p>This left me wondering -- if we're using &lt;%= syntax to write the title directly into the <code>title</code> tag - then why would we need to make it runat?</p> <p>It turns out as I suspected that the codebehind for <code>head</code> looks for an existing value inside the title tag (which would have been output here by <code>&lt;%= Html.Encode(ViewData["Title"]) %&gt;</code>. If it finds one (which will be the case for the all sample views in the MVC template) then it won't do anything further. If no title exists (if ViewData["Title"] is null or empty) it will default to whatever is defined in your view by the <code>Title</code> attribute :</p> <pre><code>&lt;%@ Page Language="C#" MasterPageFile="~/Views/Shared/RRMaster.Master" Title="View Products" AutoEventWireup="true" CodeBehind="ViewProduct.aspx.cs" Inherits="RR_MVC.Views.Products.ViewProduct" %&gt; </code></pre> <p>In my master page I would have removed the <code>runat='server'</code> tag - since I dont think I'll ever want to populate my page title from the view's <code>Title</code> property. But I'm holding off doing this pending Phil's promised blog post on the subject - in case the runat server gives me anything useful for my CSS and JS too.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload