0

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.

4

1 回答 1

3

您不能通过使用将字符串转换为整数(int) myString

设置 ViewBag 时,您可以这样做

ViewBag.RowCookie = int.Parse(userSettings);

那么它就int row = ViewBag.RowCookie;在视图中。

也就是说,在不知道你在做什么的情况下,我很难想象你会想要像这样使用 cookie 和 ViewBag 的情况。如果您不想使用超过某个索引的数组中的数据,请在创建视图模型时将其限制为该索引。那么你的 for 循环就是

@for (int i = 0; i < Model.Name.length; i++)

或者更好,将所有属性重构为 IEnumerable 集合

在视图中限制它

@for (int i = 0; i < Model.YourCollection.Count(); i++)

附带说明:

if (Request.Cookies["UserSettings"] != null)
    {
        HttpCookie myCookie = new HttpCookie("UserSettings");
        myCookie["Row"] = "5";
        myCookie.Expires = DateTime.Now.AddDays(1d);
        Response.Cookies.Add(myCookie);
    }

你确定你不是那个意思Request.Cookies["UserSettings"] == null

于 2012-05-17T05:35:50.093 回答