title: how to get data from cookie to view, C# in mvc3 using Viewbag
body: <p>This is the first time for writing C# in MVC. I add the row value to cookie and want it to genrate the number of rows, but I don't know how to do it.</p>
  
  <p>If you guys have better solutions, I will be appreciated. :)</p>
  
  <p>First, Create cookie</p>
  
  <pre><code>if (Request.Cookies["UserSettings"] != null)
          {
              HttpCookie myCookie = new HttpCookie("UserSettings");
              myCookie["Row"] = "5";
              myCookie.Expires = DateTime.Now.AddDays(1d);
              Response.Cookies.Add(myCookie);
          }
  </code></pre>
  
  <p>Second, Read Cookie,  in Controller read rows from cookie and then send through "Viewbag.RowCookie" to view</p>
  
  <pre><code> if (Request.Cookies["UserSettings"] != null)
          {
              string userSettings;
              if (Request.Cookies["UserSettings"]["Row"] != null)
              {
                  userSettings = Request.Cookies["UserSettings"]["Row"];
                  ViewBag.RowCookie = userSettings;
              }
  
          }
          return View();
  </code></pre>
  
  <p>Finally, in View, Then error appears when click the page. (Note I checked the row value is fine in another page.)</p>
  
  <pre><code>   @{int row = 3 ;
        row = (int)ViewBag.RowCookie; } // the problem is this line
  
       @for (int i = 0; i &lt; row ; i++)
      {
          &lt;tr&gt;
              &lt;td&gt;
                  &lt;p&gt;
                      @Html.Label("Name")
                      @Html.EditorFor(model =&gt; model.Name[i])&lt;/p&gt;
              &lt;/td&gt;
              &lt;td&gt;
                  &lt;p&gt;
                      @Html.Label("Prob" + (i+1))
                      @Html.EditorFor(model =&gt; model.Prop[i])&lt;/p&gt;
              &lt;/td&gt;
              &lt;td&gt;
                  &lt;p&gt;
                      @Html.Label("Forecast" + (i+1))
                      @Html.EditorFor(model =&gt; model.Forecast[i])&lt;/p&gt;
              &lt;/td&gt;
              &lt;td&gt; &lt;p&gt;
                      @Html.DisplayFor(model =&gt; model.AxB[i])
                    &lt;/p&gt;
              &lt;/td&gt;
               &lt;td&gt; &lt;p&gt;
                      @Html.DisplayFor(model =&gt; model.PowAxB[i])
                    &lt;/p&gt;
              &lt;/td&gt;
          &lt;/tr&gt;
  </code></pre>
  
  <p>Thank you all for helping.</p>