title: MVC Persist Model per Browser Tab
body: <p>I have an MVC app and I've run into a problem with modern multitab browsers.</p>
  
  <p>I have a screen that creates a model and stores it in this.TempData["MyViewModel"]</p>
  
  <p>I then open the same screen in a 2nd tab and as it calls the same controller methods this.TempData["MyViewModel"] is once again set.</p>
  
  <p>If I then go back to Tab 1 and refresh the page, I am presented with the data I entered in Tab 2.</p>
  
  <p>Is there a way to store data in TempData uniquely per browser tab ?</p>
  
  <p>I have toyed with the idea of creating a unique TempData key and persist it between requests using either the querystring or a hidden field but this seems messy.</p>
  
  <p>Any ideas / advice would be most welcome. :o)</p>
  
  <hr>
  
  <p>What I have so far is a concept of a 'ProcessID'.</p>
  
  <p>In my first partial view I have a form with a hidden field which is loosely bound to my Model.ProcessID.  When the form is posted this hidden field ProcessID is used as the TempData key... </p>
  
  <p>Example:</p>
  
  <pre><code>public sealed class MyViewModel
  {
      public MyViewModel()
      {
          this.ProcessID = Guid.NewGuid().ToString();
      }
  
      public string ProcessId { get; set; }
      // other fields
  }
  </code></pre>
  
  <p>Partial View 1:</p>
  
  <pre><code>@model Models.MyViewModel
  
  @using (Ajax.BeginForm("PartialView1", "Home", new { }, new AjaxOptions() { UpdateTargetId = "myDivToUpdate" }, new { }))
  {
      @Html.HiddenFor(m =&gt; m.ProcessId);
  
      // other fields...
  
      &lt;input type="submit" value="next" /&gt;
  }
  
  public ActionResult PartialView1(FormCollection form)
  {
      return this.PartialView("PartialView1", new Models.MyViewModel());
  }
  
  [HttpPost]
  public ActionResult PartialView1(FormCollection form)
  {    
      Models.MyViewModel vm = new Models.MyViewModel();    
  
      this.UpdateModel(vm, form);
  
      this.TempData[vm.ProcessId] = vm;
  
      return this.PartialView("PartialView2", vm);
  } 
  </code></pre>
  
  <p>In my 2nd partial view form I once again have a hidden field loosely bound to the same Model.ProcessID.  When this form is posted I can use the Model.ProcessID to retrieve my viewmodel from TempData and update it: </p>
  
  <p>Partial View 2:</p>
  
  <pre><code>@model Models.MyViewModel
  
  @using (Ajax.BeginForm("PartialView2", "Home", new { }, new AjaxOptions() { UpdateTargetId = "myDivToUpdate" }, new { }))
  {
      @Html.HiddenFor(m =&gt; m.ProcessId);
  
      // other fields (different to partial view 1)...
  
      &lt;input type="submit" value="finish" /&gt;
  }
  
  [HttpPost]
  public ActionResult PartialView2(FormCollection form, Models.MyViewModel vm)
  {
      vm = (this.TempData[vm.ProcessId] as Models.MyViewModel);
  
      this.UpdateModel(vm, form);
  
      return this.Json(new { result = true, message = "success" }, JsonRequestBehavior.AllowGet);
  }
  </code></pre>