title: Can an HtmlHelper library be compatible with both MVC-3 and MVC-4?
body: <p>I am trying to create an HtmlHelper library that will work in both MVC-3 and MVC-4 projects.</p>
  
  <p>I've been able to get a library that is compatible between MVC-2 and MVC-3 by setting the framework reference in the library to MVC-2, but MVC-2 is not the concern.</p>
  
  <p>If I set the framework reference in the library to MVC-3, when an MVC-4 project uses one of the helpers, the method in the helper-library thows an <code>Object reference not set to an instance of an object.</code> exception.</p>
  
  <p>The helper has a signature like this: </p>
  
  <pre><code>public static IHtmlString InputTagFor&lt;TModel, TValue&gt;(this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TValue&gt;&gt; expression)
  </code></pre>
  
  <p>And the null reference exception comes at this point in the method:</p>
  
  <pre><code>var value = expression.Compile()(htmlHelper.ViewData.Model).ToString();
  </code></pre>
  
  <p>because htmlHelper.ViewData.Model is <code>null</code>. </p>
  
  <p>If I switch the framework reference to MVC-4, (and system.web.webpages to v2) it all works in an MVC-4 app; but, of course, it wont' work in an MVC-3 app.</p>
  
  <p><strong>So, my question is</strong>: is it possible to Create an HtmlHelper library that is compatible between the these fraemwork versions, and how?</p>
  
  <p><strong>update</strong> Screenshots of the helper-method at a break-point, with the watch window showing values for the htmlHelper...</p>
  
  <h3>Helper method invoked from an MVC-3 app:</h3>
  
  <p><img src="https://i.stack.imgur.com/mcpHP.jpg" alt="Library helper invoked from an MVC-3 app"></p>
  
  <h3>Helper method invoked from an MVC-4 app:</h3>
  
  <p><img src="https://i.stack.imgur.com/t322y.jpg" alt="Library helper invoked from an MVC-4 app"></p>
  
  <p>...and for the record the model <code>HomePage</code> is defined independently, but identically inside each MVC app with just one field (<code>TestStringField</code>), and the controller action is returning thusly:</p>
  
  <pre><code>return View(new HomePage{TestStringField = "a string value"});
  </code></pre>
  
  <p>While the helper is being called from a strongly-typed (to <code>HomePage</code>) Razor view in a like this:</p>
  
  <pre><code>@Html.InputTagFor(model =&gt; model.TestStringField)   
  </code></pre>