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.
If you guys have better solutions, I will be appreciated. :)
First, Create cookie
if (Request.Cookies["UserSettings"] != null)
{
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["Row"] = "5";
myCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(myCookie);
}
Second, Read Cookie, in Controller read rows from cookie and then send through "Viewbag.RowCookie" to view
if (Request.Cookies["UserSettings"] != null)
{
string userSettings;
if (Request.Cookies["UserSettings"]["Row"] != null)
{
userSettings = Request.Cookies["UserSettings"]["Row"];
ViewBag.RowCookie = userSettings;
}
}
return View();
Finally, in View, Then error appears when click the page. (Note I checked the row value is fine in another page.)
@{int row = 3 ;
row = (int)ViewBag.RowCookie; } // the problem is this line
@for (int i = 0; i < row ; i++)
{
<tr>
<td>
<p>
@Html.Label("Name")
@Html.EditorFor(model => model.Name[i])</p>
</td>
<td>
<p>
@Html.Label("Prob" + (i+1))
@Html.EditorFor(model => model.Prop[i])</p>
</td>
<td>
<p>
@Html.Label("Forecast" + (i+1))
@Html.EditorFor(model => model.Forecast[i])</p>
</td>
<td> <p>
@Html.DisplayFor(model => model.AxB[i])
</p>
</td>
<td> <p>
@Html.DisplayFor(model => model.PowAxB[i])
</p>
</td>
</tr>
Thank you all for helping.