title: View data dictionary overriding model data in ASP.NET MVC
body: <p>I have a view to create a user as follows.</p>
  
  <pre><code>&lt;% using (Html.BeginForm("SaveUser", "Security")) {%&gt;
      &lt;p&gt;
          &lt;label for="UserName"&gt;UserName:&lt;/label&gt;
          &lt;%= Html.TextBox("UserName") %&gt;
          &lt;%= Html.ValidationMessage("UserName", "*") %&gt;
      &lt;/p&gt;
      &lt;p&gt;
          &lt;label for="Password"&gt;Password:&lt;/label&gt;
          &lt;%= Html.TextBox("Password") %&gt;
          &lt;%= Html.ValidationMessage("Password", "*") %&gt;
      &lt;/p&gt;
      &lt;p&gt;
          &lt;input type="submit" value="Create" /&gt;
      &lt;/p&gt;
  &lt;}%&gt;
  </code></pre>
  
  <p>When the "Create" button is clicked, the HTML form is posted to an action called "SaveUser" that accepts the "POST" verb only as follows.</p>
  
  <pre><code>[AcceptVerbs(HttpVerbs.Post)]
  public ActionResult SaveUser( UserViewModel user)
  {
      //user.Id is zero before save
      //Save the user.  Code omitted...
      //user.Id is now greater than zero
      //redirect to edit user view
      return View("EditUser", user );
  }
  </code></pre>
  
  <p>After the user is saved, the page is redirected to the "EditUser" view with</p>
  
  <pre><code>&lt;p&gt;
      &lt;label for="Id"&gt;Id:&lt;/label&gt;
      &lt;%= Html.Hidden("Id", Model.Id)%&gt;
  &lt;/p&gt;
  </code></pre>
  
  <p>Here is the problem: the value for the hidden field kept showing up as zero though. <code>Model.Id</code> is greater than zero.  It seemed that something else is overriding the model view value.  <code>ViewDataDictonary</code> was a suspect.  So a line is added before returning the view in the action as follows.</p>
  
  <pre><code>[AcceptVerbs(HttpVerbs.Post)]
  public ActionResult SaveUser( UserViewModel user)
  {
      //user.Id is zero before save
      //Save the user.  Code omitted...
      //user.Id is now greater than zero
  
      //clear the view data
      ViewData = new ViewDataDictionary();
      //redirect to edit user view
      return View( "EditUser", user);
  }
  </code></pre>
  
  <p>Sure enough, this worked.  The hidden field now has a value of the correct user ID.</p>
  
  <p><strong>We found a way to treat the symptom, but where is the source of the problem?</strong></p>
  
  <p>I don't like the idea of clearing view data dictionary every time before a returning another view.</p>