find a location for property in a new city

Saturday 13 August 2011

ASP.NET MVC Checkbox has a hidden input too

I noticed strange behaviour whilst coding and ASP.NET MVC CheckBox Html Helper. I noticed that the field which was in part of a GET form was creating the query string with the same field in it twice. When the box was checked one parameter was true and the other was false.

Say I have a boolean field, MyField, that I am creating a checkbox for. I would write this: @Html.CheckBox("MyField"). You would expect this to output a single check box but if you actually look at the HTML that is generated you will notice that is also creates a hidden field.



I found out the the reason for this is written within the ASP.NET MVC source code:
if (inputType == InputType.CheckBox) {
    // Render an additional  for checkboxes. This
    // addresses scenarios where unchecked checkboxes are not sent in the request.
    // Sending a hidden input makes it possible to know that the checkbox was present
    // on the page when the request was submitted.
    StringBuilder inputItemBuilder = new StringBuilder();
    inputItemBuilder.Append(tagBuilder.ToString(TagRenderMode.SelfClosing));

    TagBuilder hiddenInput = new TagBuilder("input");
    hiddenInput.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.Hidden));
    hiddenInput.MergeAttribute("name", name);
    hiddenInput.MergeAttribute("value", "false");
    inputItemBuilder.Append(hiddenInput.ToString(TagRenderMode.SelfClosing));
    return inputItemBuilder.ToString();
}

I appreciate the reasoning behind this but in my scenario MyField is part of a ViewModel that is being sent with the form and of course boolean values are False by default so this is wasted on my scenario.

Another reason I do not like this is because I am using the GET method on my form the user will see this oddity in the querystring. Worse still, they be a developer and judge my code as rubbish not knowing it is the doing of ASP.NET MVC. I can't have that! ;)

Solution

Simple solution really. Write the HTML you want in HTML, forget about the HtmlHelper:
<input type="checkbox" name="MyField" value="true" id="MyField"
@Html.Raw((Model.MyField) ? "checked=\"checked\"" : "") />

Remember the value="true" because the default value to be sent is "on" if it is checked, which obviously can't be parsed to a Boolean.

Obviously, this doesn't look that clean but I will continue to do this on forms that use the GET method.

Follow britishdev on Twitter

45 comments:

  1. You, sir, just helped me out of 3-hrs nightmare hunt. Thank you!

    ReplyDelete
    Replies
    1. I am writing this comment with tears of joy. My marriage fell apart after 6 months because my mother In-law asked my husband to divorce me and marriage the woman she betroth to him as his wife. All this drama started happening in our marriage and my husband left me and our one month baby just so he could do as his mom wants him to.I was in tears and shattered for 6 months because I could not imagine my whole life crumbling in front of me. I could not continue with work and baby responsibilities so I quit working. Things became more difficult until my best friend advised me to meet a love doctor that fixed her marriage with a RETURN LOVER SPELL that works as fast as 12 hours after casting the spell. I concord and decided to contact this spell doctor and guess what. My husband came to my mom house with his family in less than 12 hours after casting the spell. Even his mom came back asking me for forgiveness and also to reconcile with my husband who left me. They have been coming for the past 3 days and now everyone is asking me to take him back. I am so grateful for what this love spell doctor has done for me. I am thinking of accepting his apologize and move on as family just as my mom advised.Anyone who wants their lover back should write to love doctor on Love Spell doctor on lovespelldoctor0@gmail.com God bless you as you find your happiness through this testimony.

      Delete
  2. Thanks, was pulling my hair out over this!

    ReplyDelete
  3. Thank you! Thank you! Thank you! This was spot on and solved my problem

    ReplyDelete
    Replies
    1. Love spell doctor has brought my husband back to me after 6 months of separation. My husband left me and wanted a divorce because of a young girl who is young enough to be her daughter. Your love spell has reunited my family once again after mourning and tears that I am now a single mom, but my teas has turn to Joy with your amazing return lover spell.
      I am grateful for everything. Anyone experiencing heartbreak and needs their lover back should contact lovespelldoctor0@gmail.com and that will be the end of your problems in that relationship.
















      Love spell doctor has brought my husband back to me after 6 months of separation. My husband left me and wanted a divorce because of a young girl who is young enough to be her daughter. Your love spell has reunited my family once again after mourning and tears that I am now a single mom, but my teas has turn to Joy with your amazing return lover spell.
      I am grateful for everything. Anyone experiencing heartbreak and needs their lover back should contact lovespelldoctor0@gmail.com and that will be the end of your problems in that relationship.





















      Love spell doctor has brought my husband back to me after 6 months of separation. My husband left me and wanted a divorce because of a young girl who is young enough to be her daughter. Your love spell has reunited my family once again after mourning and tears that I am now a single mom, but my teas has turn to Joy with your amazing return lover spell.
      I am grateful for everything. Anyone experiencing heartbreak and needs their lover back should contact lovespelldoctor0@gmail.com and that will be the end of your problems in that relationship.

      Delete
  4. Many Many thanks. Now my problem is resolved.
    I was wasting 2-3 hr every night since 1 week and now my issue is resolved. It's really great.

    ReplyDelete
  5. Motifz Designer Lawn. 1, 2 & 3 Piece Unstitched Premium Embroidered Lawn 2019, Premium embroidered Lawn, Premium lawn, Premium lawn 2019, Motifz, Premium lawn in Pakistan. Shipping worldwide. Stitching option available.

    ReplyDelete
  6. Yes i am totally agreed with this article and i just want say that this article is very nice and very informative article.I will make sure to be reading your blog more. You made a good point but I can't help but wonder, what about the other side? !!!!!!Thanks this person tried to unlock your phone

    ReplyDelete
  7. It should be noted that whilst ordering papers for sale at paper writing service, you can get unkind attitude. In case you feel that the bureau is trying to cheat you, don't buy term paper from it. Wordpress Tips

    ReplyDelete
  8. I have to search sites with relevant information on given topic and provide them to teacher our opinion and the article. สมัครเน็ตทรู

    ReplyDelete
  9. That definitely possibly an amazing organize i always in truth definitely relished checking out. It's not necessarily specifically frequent i always add some choice to identify a selected matter. microsoft office 365 product key

    ReplyDelete
  10. Thanks for this article very helpful. thanks. Adele net worth

    ReplyDelete
  11. Great article Lot's of information to Read...Great Man Keep Posting and update to People..Thanks Adele net worth

    ReplyDelete
  12. Snappy disclaimer: I AM NOT BASHING ANYONE! Indeed, I was yelling that. This segment of the article is mentioning to you what I know, read, hear and involvement with gaming.
    Subway surfer hack

    ReplyDelete
  13. Love spell doctor has brought my husband back to me after 6 months of separation. My husband left me and wanted a divorce because of a young girl who is young enough to be her daughter. Your love spell has reunited my family once again after mourning and tears that I am now a single mom, but my teas has turn to Joy with your amazing return lover spell.
    I am grateful for everything. Anyone experiencing heartbreak and needs their lover back should contact lovespelldoctor0@gmail.com and that will be the end of your problems in that relationship.

    ReplyDelete
  14. Very efficiently written information. It will be beneficial to anybody who utilizes it, including me. Keep up the good work. For sure i will check out more posts. This site seems to get a good amount of visitors. hidden marriage

    ReplyDelete
  15. i will love to share my testimony to you all the people in world i got married to my husband about 2 year ago we start having problems at home like we stop sleeping on the same bed,fighting about little things he always comes home late at night,drinking too much and sleeping with other women out side i have never love any man in my life except him. he is the father of my child and i don't want to loose him because we have worked so hard together to become what we are and have today .few month ago he now decided to live me and the kid,being a single mother can be hard sometimes and so i have nobody to turn to and i was heart broken.i called my mom and explain every thing to her,my mother told me about DR.kuta how he helped her solve the problem between her and my dad i was surprise about it because they have been without each other for three and a half years and it was like a miracle how they came back to each other. i was directed to DR. kuta on his email. (drkutaherbalcenter@gmail.com) and explain everything to him,so he promise me not to worry that he will cast a spell and make things come back to how we where so much in love again and that it was another female spirit that was controlling my husband he told me that my problem will be solved within two days if i believe i said OK So he cast a spell for me and after two days my love came back asking me to forgive him i Am so happy now. so that why i decided to share my experience with every body that have such problem contact Dr kuta the great spell caster on his email addresses (drkutaherbalcenter@gmail.com)or whatsapp Dr kuta on (+2347054547814)

    ReplyDelete
  16. Buy online wholesale printed custom lipstick boxes and packaging at easy prices and shipping worldwide, with 24/7 customer support. Get a free custom quote now!!

    ReplyDelete
  17. Blackbird packaging provide you with any size, shape design, custom e liquid boxes sooner than any other packaging competitor in the market

    ReplyDelete
  18. Packaging town is a one-stop solution for the short-run cbd facial oil boxes needs, and supplies. At affordable prices. Request a free quote now.

    ReplyDelete
  19. HAVE YOU BEEN IN SEARCH FOR GENUINE HACKER'S ONLINE?. HAVE YOU LOST YOUR MONEY TO BINARY OPTION SCAM OR ANY ONLINE SCAM WHATSOEVER?. WELL, YOU HAVE FOUND REDEMPTION IN ASORE CORP.
    asorehackcorp@gmail.com

    Asore Corp is a group of multinational Hacker's, an affiliate of Evil Corp. We make sure by all means necessary that our clients get the best of services on a🔐PAYMENT AFTER JOB IS DONE BASIS✅. Rather than send money and trust a criminal to fulfill your deal, you can make sure the job is done before WORKMANSHIP is paid for. You'll get excellent customer service.
    That's a 100% guarantee. Our Cyber security Technicians are on standby 24/7 to receive your job requests.

    ⚠️ BEWARE OF FRAUDSTARS looking to hoax.
    if you have been a VICTIM, contact : ✉️cyberprecinct@gmail.com for directives.
    Here, it's always a win for you.

    🔸OUR SERVICES🔸
    ➡️Binary Option funds recovery
    ➡️Social media hack
    ➡️Recovery of loan scam
    ➡️Credit repair (Equifax,Experian,Transunion)
    ➡️E mail hack
    ➡️College score upgrade
    ➡️Android & iPhone Hack
    ➡️Website design
    ➡️Website hack
    And lots more.

    DISCLAIMER: Asore Cyber Corp accepts no responsibility for any information,previously given to anybody by clients on as regarding the job. Asore Cyber Corp will not distribute contact information collected on any hacking job other than in the Asore corps Hacker's listings themselves, and will not sell contact information to third parties.

    CONTACT INFO:
    📧 asorehackcorp@gmail.com
    cyberprecinct@gmail.com

    Copyright ©️
    Asore Cyber Corp 2021.
    All rights reserved.

    ReplyDelete
  20. buy best vaccum cleaners online from alfatah at best prices. Get free shipping

    ReplyDelete
  21. buy best vaccum cleaners online from alfatah at best prices. Get free shipping

    ReplyDelete
  22. buy grocery online in lahore in pakistan from alfatah at best prices. Get free shipping

    ReplyDelete
  23. Explore the profiles of guwahati escorts, guwahati call girls, call girls in guwahati and
    escorts in guwahati for female companionship in top rated hotels. Get affordable
    escort services in guwahati hotels now.Nitu Roy is a popular and
    trusted name in the field of call girl service.
    Guwahati Call Girl
    Call Girl in Guwahati

    ReplyDelete
  24. Buy wedding cookie boxes wholesale online from Blackbird Packaging at best prices. Get free shipping.

    ReplyDelete
  25. you made some tight points there. I looked on the web for the difficulty and found most individuals will approve together with your blog 3d configurator

    ReplyDelete
  26. Packaging town is a one stop solution for the short-run custom soap boxes needs and supplies. At affordable prices. Request a free quote now.

    ReplyDelete
  27. Blackbird packaging provide you with any size, shape design, wedding cookie boxes wholesale sooner than any other packaging competitor in the market

    ReplyDelete
  28. Buy shorts pakistan from ndure at best prices delivered at your doorstep. Get free shipping

    ReplyDelete
  29. Buy gym trousers mens online pakistan online dshred at best prices delivered at your doorstep. Get free shipping

    ReplyDelete
  30. Buy basic tees online from ndure at easy prices delivered at your doorstep. Get free shipping

    ReplyDelete
  31. Now You can buy lactogen 2 400g price in Pakistan from medisense where all kind of medicine and baby foods are available. Quick delivery.

    ReplyDelete
  32. Now you can buy all kind of medicines from medisense Pakistan online pharmacy. Best quality and Quick delivery.

    ReplyDelete
  33. Buy Good quality insulins online in Pakistan with affordable rates at your door step. Fast delivery.

    ReplyDelete
  34. Buy men clothing online in Pakistan from Al-Fatah at best prices delivered at your doorstep. Get free shipping.

    ReplyDelete
  35. NDURE brings you its wide range of mens cotton t shirts online in pakistan. Now you can buy your favorites with just a tap You can find our t shirts online by logging into our site Our shirts are made with pure fabric that makes you stand out So don t wait around and shop from our collection of online t shirts.

    ReplyDelete
  36. Somebody Sometimes with visits your website consistently and prescribed it as far as I can tell to peruse also. The method for composing is magnificent furthermore the substance is first class. A debt of gratitude is in order for that knowledge you give the perusers! numéro voyance gratuit

    ReplyDelete
  37. This is an incredible rousing article.I am basically satisfied with your great work.You put truly exceptionally accommodating data... Parallel space filehippo

    ReplyDelete
  38. Your blogs are great.Are you also searching for Nursing assignment writers ? we are the best solution for you. We are best known for delivering great nursing assignments.

    ReplyDelete
  39. Hello viewer am Albert mike from Kenya 30 years old am here to share my testimony on how i joined the brotherhood of illuminati.. four months back when i wanted to join the brotherhood i was scammed by fake agents and people pretending to be Grand Master use the website.. until i met a friend MR BERRY WARD who gave me the genuine procedures i followed and made me a member of the great brotherhood of illuminati. today i am living a good life and i have enough money to do all i ever wanted .if u are interested and u need the help of my Initiator Berry.send email-grandmasterilluminati29@gmail.com or Whats'App MR Berry ward +1(720) 803-2932 thanks Berry, am living the dream i will forever be grateful

    ReplyDelete