Based on the answer here: How can I write and read bool values into/from cookies?, I'm trying to implement cookie reading/writing code.
I've got a series of checkboxes on a page whose checked state should be saved to/as cookies; when the page [re]loads, the last state should inform the checkboxes whether they should be checked or not. But it's not working. Here are the pertinent parts of the page:
@{
bool twitterSelected = false;
. . .
var selectTwitterCookie = Request.Cookies["selectTwitter"];
. . .
if (selectTwitterCookie != null)
{
twitterSelected = Convert.ToBoolean(selectTwitterCookie);
}
. . .
if (IsPost)
{
Response.Cookies["selectTwitter"].Value = twitterSelected.ToString();
Response.Cookies["selectTwitter"].Expires = DateTime.Now.AddYears(1);
. . .
}
}
<section class="featured">
<div class="content-wrapper">
<h1>Stuff!!!</h1>
<form method="POST">
<fieldset>
<legend>Opt In or Out</legend>
<input type="checkbox" id="selectTwitter" name="selectTwitter" checked=@twitterSelected>I'm Twitterpated!</input><br />
<input type="submit" id="btnSubmit" name="btnSubmit" value="Save Config changes"</input>
</fieldset>
</form>
</div>
</section>
However, not only does the checkbox not get restored to the state I saved after posting, on navigating away and then back to the page, I get, "System.InvalidCastException was unhandled by user code HResult=-2147467262 Message=Unable to cast object of type 'System.Web.HttpCookie' to type 'System.IConvertible'. Source=mscorlib StackTrace: at System.Convert.ToBoolean(Object value) at ASP._Page_About_cshtml.Execute() in c:\DuckbilledPlatypi\About.cshtml:line 27 . . . InnerException:"
And here is the YSOD:
Server Error in '/' Application. Unable to cast object of type 'System.Web.HttpCookie' to type 'System.IConvertible'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Unable to cast object of type 'System.Web.HttpCookie' to type 'System.IConvertible'. Source Error: Line 25: //bool.TryParse(selectTwitterCookie, out twitterSelected); Line 26: //Alternatively, could use: Line 27: twitterSelected = Convert.ToBoolean(selectTwitterCookie); Line 28: } Line 29: if (selectBingCookie != null) Source File: c:\DuckbilledPlatypi\About.cshtml Line: 27 Stack Trace: [InvalidCastException: Unable to cast object of type 'System.Web.HttpCookie' to type 'System.IConvertible'.] System.Convert.ToBoolean(Object value) +18 ASP._Page_About_cshtml.Execute() in c:\DuckbilledPlatypi\About.cshtml:27 System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197 System.Web.WebPages.WebPage.ExecutePageHierarchy(IEnumerable`1 executors) +69 System.Web.WebPages.WebPage.ExecutePageHierarchy() +151 System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76 System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal(HttpContextBase httpContext) +114 Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18033
So how can I successfully save and restore the state of checkboxes?
changing this:
twitterSelected = Convert.ToBoolean(selectTwitterCookie);
...to this:
twitterSelected = Convert.ToBoolean(selectTwitterCookie.Value);
...got rid of the err msg, but still does not restore the value (checked state) I save.
Bizarrely enough, two of the checkboxes are now working (two that I checked remain checked). Why the other ones don't is a mystery so far - the code for them all is identical, or at least seems so so far. I'll have to dig deeper...
They only appeared to be working, because there was a mismatch in the string used to set them, and the one used to restore them. I have now changed the default value of the bools from false to true, and all of the checkboxes are always checked now (after posting/on [re]loading the page). So, I still don't know why the following does not work:
bool twitterSelected = true;
var selectTwitterCookie = Request.Cookies["selectTwitter"];
if (selectTwitterCookie != null)
{
twitterSelected = Convert.ToBoolean(selectTwitterCookie.Value);
}
. . .
if (IsPost)
{
Response.Cookies["selectTwitter"].Value = twitterSelected.ToString();
<input type="checkbox" id="selectTwitter" name="selectTwitter" checked=@twitterSelected>I'm Twitterpated!</input><br />
These permutations also do not work:
<input type="checkbox" id="selectTwitter" name="selectTwitter" [email protected]()>I'm Twitterpated!</input><br />
<input type="checkbox" id="selectTwitter" name="selectTwitter" checked="@twitterSelected">I'm Twitterpated!</input><br />
I've even tried this:
<input type="checkbox" id="selectTwitter" name="selectTwitter" [email protected](twitterSelected)>I'm Twitterpated!</input><br />
...but it makes no diff - the checkboxes simply won't respect the cookie vals. Or, rather, the vals are not being set: after unchecking a box, all the cookies are "True" whereas the one unchecked should be false...
Another attempt I made -- because I saw one of the cookies (secure_session) had a value of "true" -- was adding this code in case case was important:
if (IsPost)
{
Response.Cookies["selectTwitter"].Value = twitterSelected.ToString().ToLower();
. . .
...again, alas, no joy here in Mudville: mighty case-y has struck out.
The problem is in my [il]logic: the IsPost section/event/condition is not setting the cookie values to current reality (the checked state of the checkbox).
I tested by forcing the val like so in the "if (IsPost) {}" section:
Response.Cookies["selectTwitter"].Value = "false";
...and it works fine. But how to make it really work is still a conundrum. Is there a jQuery "httppost" event where I could set all the cookies based on the state of the checkboxes? Or is there a checkboxChange or -Toggle event where I can set the cookie val for the "this" checkbox?
I tried this, too:
if (IsPost)
{
Response.Cookies["selectTwitter"].Value = Request["selectTwitter"]; //"false";
. . .
<form method="POST">
. . .
<input type="checkbox" id="selectTwitter" name="selectTwitter" checked=@twitterSelected>I'm Twitterpated!</input><br />
...but still no go; it's not a problem that the name/id of the text input control is the same as the name of the cookie value, is it?
Check out the OPTIONS response header ACCESS-CONTROL-ALLOW-CREDENTIAL whether it is set to true . If the server doesn't allow credentials being sent along, the browser will just not attach cookies and authorization headers. So this could be another reason why the cookies are missing in the POST cross-site request.
Google Chrome Click Content settings in the Privacy section. Ensure that the bullet for "Allow local data to be set (recommended)" is checked. Also ensure that "Block third-party cookies and site data" is unchecked.
I got the answer from Mike "Mikesdotnetting" Brind over at http://forums.asp.net/p/1910373/5408967.aspx/1?Re+How+can+I+access+html+elements+in+the+IsPost+section+of+the+razor+code+
As the error is trying to tell you, selectTwitterCookie
is an HttpCookie
instance containing information about the cookie.
It doesn't make sense to convert that to a boolean.
You may want the Value
property, which returns a string with the actual value of the cookie.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With