title: Razor partial view prefix field names
body: <p>When using Razor to render a form for a complex Model that has sub-models, we'd usually use Partial Views to render the sub-models.</p>
  
  <p>Simple example Model:</p>
  
  <pre><code>public class BlogPost
  {
      public string Content { get; set; }
      public List&lt;Comment&gt; Comments { get; set; }
  }
  
  public class Comment
  {
      public string Content { get; set; }
  }
  </code></pre>
  
  <p>BlogPost.cshtml:</p>
  
  <pre><code>@model BlogPost
  
  @Html.TextAreaFor(x =&gt; x.Content)
  
  @for (int i = 0; i &lt; Model.Comments.Count; i++)
  {
      @Html.Partial('Comment', Model.Comments[i])
  }
  </code></pre>
  
  <p>Comment.cshtml:</p>
  
  <pre><code>@model Comment
  
  @Html.TextAreaFor(x =&gt; x.Content)
  </code></pre>
  
  <p><strong>Now for the issue:</strong></p>
  
  <p>Say we want to send the values of all fields to a controller action that takes <code>BlogPost</code> as a parameter. The fields are going to be posted back to the controller like so:</p>
  
  <p>Content=The+content+of+the+BlogPost&amp;Content=The+first+Comment&amp;Content=The+second+Comment</p>
  
  <p>But what we need to have MVC map them correctly to the <code>BlogPost</code> view model, we need this naming convention:</p>
  
  <p>Content=The+content+of+the+BlogPost&amp;Comments[0].Content=The+first+Comment&amp;Comments[1].Content=The+second+Comment</p>
  
  <p>How can this be achieved in a clean way? We can only think of two ways which both seem to compromise the design:</p>
  
  <ul>
  <li>Either we pass the <code>BlogPost</code> as a model to the partial view such that we can define the text area like so: <code>@Html.TextAreaFor(x =&gt; x.Comments[i].Content)</code>. But this means we couple the partial view for comments to the parent view model - you could think of a scenario where the same partial view should be used in a different context, which is not possible if the partial view depends on the parent view model. Futhermore, the <code>i</code> would have to be passed to the partial view somehow.</li>
  <li>Or we fall back to explicitely defining the name of every single field with strings: <code>@Html.TextArea(ViewBag.Prefix + ".Content")</code>.</li>
  </ul>
  
  <p>Is there any way to tell the partial view to apply a certain prefix to <em>all</em> field names?</p>