2015-03-18 55 views
0

所以我制作了2页,一个用于设置,另一个用于标签和图像。我想要的东西是当没有饼干img_gm.BorderWidth和img_gm.Bordercolor将默认为1和黑色,但它似乎总是出现在解释错误“img_gm.BorderWidth = Convert.ToInt32(cookie [”width“]] );”任何帮助将不胜感激。ASP.NET为cookies设置默认值

*我把文本框,下拉列表和单选按钮设置页来获得饼干[“宽度”],饼干[“颜色”和饼干的输入[“字体”]

保护无效的Page_Load (对象发件人,EventArgs的){

HttpCookie cookie = Request.Cookies["settings"]; 
    if (Request.Cookies.AllKeys.Contains("settings") == null) 
    { 
     cookie["width"] = "1"; 
     cookie["color"] = "Black"; 
     cookie.Expires = DateTime.Now.AddDays(14); 
     Response.Cookies.Add(cookie); 
    } 
    else 
    { 

     img_gm.BorderWidth = Convert.ToInt32(cookie["width"]); 
     img_gm.BorderColor = System.Drawing.Color.FromName(cookie["color"]); 
     switch (cookie["font"]) 
     { 
      case "Bold": 
       lbl_desc.Font.Bold = true; 
       break; 
      case "Italic": 
       lbl_desc.Font.Italic = true; 
       break; 
      case "Overline": 
       lbl_desc.Font.Overline = true; 
       break; 
      case "Underline": 
       lbl_desc.Font.Underline = true; 
       break; 
     } 

    } 
+0

你为什么要检查if块中的'Response.Cookes.AllKeys'?也许它应该是'请求'? – 2015-03-18 20:56:44

+0

噢,我混淆了这些之间,我在我的代码中写请求,但它仍然给我一个错误“img_gm.BorderWidth = Convert.ToInt32(cookie [”width“]);” – AHA27 2015-03-18 20:58:41

+0

如果你设置断点并检查'cookie [“width”]的值,它有什么值?也许它有一些旧的测试值不是整数,所以它在解析过程中失败? cookie只需要在浏览器中清除? – 2015-03-18 21:00:50

回答

0

一个巧妙的方法是将其更改为属性在类:

public int CookieWidth { 
    get { 
    int width; 
    var str = String.Format("{0}", cookie["width"]); 
    if (!Integer.TryParse(str, width)) { 
     width = 1; 
    } 
    return width; 
    } 
    set { 
    cookie["width"] = value; 
    } 
} 

你可以做到这一点的颜色,也。