Creating a Yes/No toggle switch for a boolean property in ASP.MVC

11. May 2013 13:20 by admin in .net, jQuery, JQuery UI, MVC

When editing boolean values in MVC the default option is to use a checkbox. This results in the following Create page when using the default scaffolding


This is fine and works OK but sometimes you want something more..’fancy’. ASP.NET MVC ships with Jquery.UI so why no use the slider of JQuery.UI to create a nice toggle switch?

In this post I will use and modify a JQuery.UI plugin that will result in the following. The plugin is based on which had some errors in my opinion.


There are a two parts to this:

  1. Create a HTMLHelper extension method that renders a <select> element for the boolean property with <option> elements for true and false
  2. Change the rendered <select> element to a jquery slider using a JQuery.UI plugin

Creating the HTMLHelper

public static class HtmlHelperExtensions
public static MvcHtmlString ToggleSwitchFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression)
return htmlHelper.DropDownListFor(expression, new[]
new SelectListItem { Text = "No", Value = "false" },
new SelectListItem { Text = "Yes", Value = "true" } 
}, new { @class = "toggleswitch" });

This adds a HTMLHelper method that renders a dropdown list which comes down to a single select HTML element. There are two options in the select : one for true and one for false. To use it we just do 

@Html.ToggleSwitchFor(model => model.CommentsEnabled)

And we get the following html

<select class="toggleswitch" data-val="true" data-val-required="The CommentsEnabled field is required." id="CommentsEnabled" name="CommentsEnabled"><option value="false">No</option><option value="true">Yes</option></select>

This is all what we need to get our JQuery plugin going.

Creating the JQuery plugin

The plugin uses the JQuery.UI slider to create a toggle switch. This means that any styling or theme you might have for the slider will work for the toggle as well. The plugin transforms the select element into two labels with a slider in between. When you click on a label or move the slider the select control will be updated as well and when you do form post the values get updated. The had two errors when I tried it

  1. The change event was just passing the change event of the slider. This meant even if the boolean property did not change (you moved the slider a little) you would still get a change event. In this version the change event is only fired when the value really changed.
  2. The plugin did not allow chaining.
  3. The normal ‘change’ event of JQuery was no longer fired. This is fixed by not having a change event on the control itself but just fire the existing change event.

To use it you need to add the CSS and JS of the plugin to your page. You also need the default JQuery UI js and css (which is not referenced by default!). Once you have done that you can activate the plugin for a control:

$(document).ready(function () {
$("#CommentsEnabled").toggleSwitch().change(function() {

I attached a sample MVC application as well as the JQuery.UI.ToggleSwitch plugin. (771,1 KB) (1,73 KB)
Samual Frutiger 9/4/2013 3:46:53 AM United States #
Samual Frutiger

I simply want to tell you that I am new to blogs and honestly loved this blog. Almost certainly I�m planning to bookmark your website . You actually come with good posts. Thanks a lot for sharing with us your web page.

Cassandra Merren 9/11/2013 10:26:13 PM United States #
Cassandra Merren

Hi, Neat distribute. Near's a problem with your site in internet explorer, would ensure this... Explicitly still is the market place principal down with a bulky percentage of people can skip the excellent writing for this reason problem.

Bill Scullawl 9/11/2013 10:27:03 PM United States #
Bill Scullawl

Hi, Neat make public. There's a problem with your locate in internet explorer, would ensure this... That is still is the market position chief down with a large percentage of people can neglect the first-rate letters for this reason problem.

Handmade Jewelry 9/24/2013 12:10:54 AM United States #
Handmade Jewelry

I am glad that it turned out so well and I hope it will continue within the future because it's so worthwhile and meaningful to the community.

Wilda Gagarin 9/24/2013 11:22:40 PM United States #
Wilda Gagarin

I was recommended this web site by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my trouble. You are wonderful! Thanks!

Tenesha Kenndy 9/26/2013 1:58:37 AM United States #
Tenesha Kenndy

Right here is the right blog for anyone who would like to understand this topic. You realize a whole lot its almost tough to argue with you (not that I personally would want to�HaHa). You certainly put a brand new spin on a topic that has been discussed for ages. Wonderful stuff, just wonderful!

Handmade Jewelry 9/30/2013 7:30:36 PM United States #
Handmade Jewelry

It�s difficult to acquire knowledgeable males and ladies within this subject, and you could be seen as you know what you are dealing with! Thanks

Copper Jewelry 10/4/2013 3:42:25 AM United States #
Copper Jewelry

Some times its a pain inside the ass to read what  weblog owners  wrote but this  site is quite   user friendly ! .

Handmade Jewelry 10/5/2013 2:00:20 AM United States #
Handmade Jewelry

you might have got a exceptional weblog here! want to develop invite posts on my weblog?

Handmade Jewelry 10/5/2013 7:12:41 PM United States #
Handmade Jewelry

Thank you for your quite good information and feedback from you. san jose used car

Copper Jewelry 10/6/2013 11:18:22 PM United States #
Copper Jewelry

hello admin, your website page�s pattern is simple and clean and i like it. Your articles are amazing. Remember to keep up the great function. Greets..

Handmade Jewelry 10/8/2013 3:07:11 AM United States #
Handmade Jewelry

I  as well  believe   thence , perfectly  pent  post! .

Handmade Jewelry 10/8/2013 10:02:41 PM United States #
Handmade Jewelry

I'm crazy about this weblog. I've visit so a lot of time to this weblog. I was identified this blog from Google. I have received a nice stuff of details. I genuinely appreciate to meet to it and i emphasize to this weblog. My curiosity to learn a lot more and much more on this weblog.

Dale Angle 10/9/2013 1:35:02 AM United States #
Dale Angle

Hey check this new project

Darrell Coran 10/9/2013 3:24:56 AM United States #
Darrell Coran

Hey check this new project

Yuk Letterman 10/9/2013 5:03:00 AM United States #
Yuk Letterman

Best advices across internet

Winifred Maes 10/9/2013 5:24:19 PM United States #
Winifred Maes

Hey check this new project

Handmade Jewelry 10/11/2013 12:36:17 AM United States #
Handmade Jewelry

I'm not certain where you are finding your information, but excellent subject. I needs to spend some time learning a lot much more or understanding a lot more. Thanks for excellent information I was searching for this details for my mission.

energooszczedne 10/12/2013 4:51:41 PM United States #

im glad to see this webpage

hareketli bayrak 10/12/2013 9:03:55 PM United States #
hareketli bayrak

WONDERFUL Post.thanks for share..more wait .. �

Copper Jewelry 10/14/2013 2:40:35 AM United States #
Copper Jewelry

A domain name is an identification label which defines a realm of administrative autonomy, authority, or control in the Internet. Domain names are also critica for domain hosting\website hosting

Handmade Jewelry 10/19/2013 1:11:51 AM United States #
Handmade Jewelry

But however, regardless how good you will be accompanied by treating a huge rig, sometime currently, you will find a situation in places ought to do selected details treating; and furthermore primarily based on your real age yet fitness level,  free of charge weight in your caravan it really is a fantastically excessive do exercises. pre owned awnings

Handmade Jewelry 11/1/2013 10:33:16 PM United States #
Handmade Jewelry

I’d always  want to be update on new  content  on this website  ,  saved to fav! .

Handmade Jewelry 11/3/2013 5:57:09 AM United States #
Handmade Jewelry

bless you with regard to the particular blog post ive actually been seeking with regard to this kind of advice on the net for sum time these days hence with thanks

Kathie Knop 11/7/2013 2:19:11 PM United States #
Kathie Knop

I don't speak english very much but i love this blog. It is interesting.

Handmade Jewelry 11/11/2013 4:55:37 AM United States #
Handmade Jewelry

Dead written    topic matter, Truly enjoyed  reading through .

Eagle Safety Products 11/12/2013 8:12:27 AM United States #
Eagle Safety Products

Hello buddie, I just wanted to tell you that this post was really beneficial for me. We were capable of take the info you so kindly published and even try it. Your blog posting genuinely worked for me and that i would want to inform your dedicated subscribers that they really have someone who's their mind fixed. Many thanks yet again for your superb posting. I've bookmarked it on my favorite internet bookmarking site and I would suggest everybody else do the exact same.

Demarcus Curts 11/12/2013 12:19:06 PM United States #
Demarcus Curts

The New IAPS Security Store:

Welding Gas 11/14/2013 7:59:43 AM United States #
Welding Gas

Hey partner, I just wanted to tell you that your blog post was precious to me. I had been fortunate to take the information you so kindly shared as well as put it to use. Your site article truly assisted me and I want to inform your committed subscribers they really have someone that has their head fixed. Thank you once again for your amazing post. I've truly book-marked this on my favorite internet book-marking internet site and I advise everybody else do the exact same.

Pat Bielefeld 11/20/2013 11:40:09 PM United States #
Pat Bielefeld

This really answered my problem, thank you!

from this source 12/17/2013 1:52:19 PM United States #
from this source

Thank you, I've recently been looking for info about this subject for a while and yours is the best I have came upon till now. But, what concerning the bottom line? Are you sure concerning the source?

att uverse coupon codes 12/20/2013 2:14:08 AM United States #
att uverse coupon codes

Hi there! I could have sworn I've been to this blog before but after browsing through some of the post I realized it's new to me. Anyways, I'm definitely glad I found it and I'll be book-marking and checking back often!

home 12/20/2013 9:11:24 AM United States #

hey there and thank you for your info � I�ve definitely picked up anything new from right here. I did however expertise several technical issues using this site, since I experienced to reload the web site a lot of times previous to I could get it to load properly. I had been wondering if your web host is OK? Not that I am complaining, but sluggish loading instances times will sometimes affect your placement in google and can damage your high quality score if advertising and marketing with Adwords. Anyway I�m adding this RSS to my e-mail and could look out for a lot more of your respective intriguing content. Ensure that you update this again very soon..

symptoms of acid reflux 1/17/2014 1:08:52 AM United States #
symptoms of acid reflux

What's up, this weekend is nice in support of me, as this moment i am reading this wonderful informative article here at my home.  <a href=>acid reflux diet</a>

visit website 1/19/2014 9:56:19 AM United States #
visit website

F*ckin' remarkable issues here. I am very glad to look your article. Thanks a lot and i'm taking a look ahead to contact you. Will you kindly drop me a mail?

Shakita 2/6/2014 5:28:35 PM United States #

Nice job on presenting the information, this was very helpful.

Acheter liquide ecigarette 2/11/2014 9:36:25 PM United States #
Acheter liquide ecigarette

Decouvrir le superbe site : <a href="">atomiseur ego-t</a><br/>

voyance tout de suite 2/12/2014 2:19:06 AM United States #
voyance tout de suite

voyance gratuite en ligne ile de france<br/>Visiter le nouveau site web : <a href="">voyance en direct</a>

ekonomia 2/17/2014 12:45:05 PM United States #

Way cool! Some very valid points! I appreciate you penning this post and the rest of the site is very good.

Keywords Jeet 2/18/2014 1:57:34 PM United States #
Keywords Jeet

You realize therefore significantly with regards to this matter, produced me in my opinion imagine it from numerous various angles. Its like women and men are not involved unless it is one thing to do with Lady gaga! Your own stuffs nice. All the time handle it up!

free ringtones iphone 4 2/22/2014 12:03:30 AM United States #
free ringtones iphone 4

nice share,Thanks for the informations dont forget to drop by my link and apply to be able to win a free iphone 5c

jewels 2/23/2014 2:18:27 PM United States #

Good job on providing the information, this was very handy.

jewels advice 2/23/2014 6:49:18 PM United States #
jewels advice

More information like this will be fantastic, hope I can come by once again and utilize it.

Kit 2/28/2014 10:54:53 PM United States #

You information has been of great help, nice work

Brandie 3/1/2014 11:28:47 PM United States #

Love your blog and the info that you are providing, keep the good stuff coming.

good 3/12/2014 6:13:26 AM United States #

I like this web blog very much, Its a very nice office to read and obtain information. "The world began without man, and it will complete itself without him." by Claude Levi-Strauss.

Best Wordpress Plugins 3/14/2014 4:14:13 PM United States #
Best Wordpress Plugins

Hi there, I discovered your web site via Google even as searching for a comparable matter, your web site got here up, it appears to be like good. I've bookmarked to favourites|added to bookmarks.

teeth whitening 3/23/2014 6:38:22 AM United States #
teeth whitening

I like your discussion, keep writing a providing info like this.

chatline 5/3/2014 2:51:13 AM United States #

I do trust all of the concepts you have presented in your post. They're very convincing and can definitely work. Nonetheless, the posts are very short for starters. Could you please extend them a bit from subsequent time? Thanks for the post.

Solomon 5/4/2014 3:21:31 PM United States #

There is definately a lot to find out about this issue. I love all the points you've made.|

Rodney 5/5/2014 7:05:09 PM United States #

Right here is the perfect blog for anyone who wishes to find out about this topic. You understand so much its almost tough to argue with you (not that I actually will need to�HaHa). You certainly put a new spin on a subject which has been discussed for years. Excellent stuff, just excellent!|

other 5/15/2014 6:10:55 PM United States #

Really nice style and design and excellent content, absolutely nothing else we require Laughing.

Opal 5/25/2014 12:42:46 AM United States #

Good day I am so happy I found your blog page, I really found you by accident, while I was browsing on Google for something else, Anyhow I am here now and would just like to say thanks a lot for a marvelous post and a all round enjoyable blog (I also love the theme/design), I don�t have time to browse it all at the minute but I have saved it and also added your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the awesome work.|

Roman 5/25/2014 4:14:24 PM United States #

Hello, I think your website might be having browser compatibility issues. When I look at your website in Ie, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, terrific blog!|

chat 6/5/2014 9:01:27 AM United States #

I dugg some of you post as I  cerebrated they were  invaluable   handy

Shaun Leslie 6/9/2014 7:16:33 PM United States #
Shaun Leslie

personally i think strongly regarding that besides appreciate reading through a lot more with this topic

Pantofi Barbatesti 6/18/2014 12:43:44 PM United States #
Pantofi Barbatesti

Given that I at first wrote above MBT sneakers at <strong><a href=""; title="Pantofi Barbatesti">Pantofi Barbatesti</a></strong>, a good deal contains transformed more than the model, and the inventor and founder contains remaining the organization. Amongst legitimate buyers, evaluations of MBT footwear are rather blended. If your self're thinking of a couple of MBT sneakers, I strongly inspire your self towards in addition read through the feedback still left inside of solution in the direction of the soon after written content, and chat towards your medical professional ahead of putting on any style of shoe that is therefore drastically choice against what yourself're applied toward, or toward deal with any fashion of suffering or trouble.

Dropbox Tips Tricks 4/29/2015 4:30:07 AM United States #
Dropbox Tips Tricks

It�s nearly impossible to find educated people about this topic, however, you seem like you know what you�re talking about! Thanks

��C 5/16/2015 12:33:59 PM United States #

merci pour ces informations

Candance Entz 6/5/2015 1:04:22 AM United States #
Candance Entz

This is exactly what I used to be seeking for, thank you

Pearline Ringhouse 6/10/2015 1:39:41 AM United States #
Pearline Ringhouse

My programmer is trying to convince me to move to .net from PHP. I have always disliked the idea because of the expenses. But he's tryiong none the less. I've been using WordPress on several websites for about a year and am worried about switching to another platform. I have heard fantastic things about Is there a way I can import all my wordpress posts into it? Any kind of help would be greatly appreciated!

Velvet Caroway 6/10/2015 1:41:19 AM United States #
Velvet Caroway

I’ll complain that you have copied materials from another source

Roberto Heisey 7/2/2015 1:21:38 PM United States #
Roberto Heisey

I truly love your site.. Pleasant colors & theme. Did you develop this web site yourself? Please reply back as I’m attempting to create my very own site and would like to learn where you got this from or exactly what the theme is named. Thank you!

Marco 7/22/2015 4:20:59 AM United States #

After looking a few days on the dilemma of how and when the human race was born, I gave birth to these hypotheses, thanks also to the differences found in Genesis between two stories that seem different, namely the creation of man on the sixth day and then the telling of the story about Adam and Eve. If we read the part of the genesis which explains the creation of man on the sixth day, and then the creation of Adam and Eve, you may notice a detail that differs between the two parts, suggesting that they are two completely different stories. In fact, in Genesis 1:26, we can see that man was created on the sixth day in the image and likeness of God, as in Genesis 5:1 (referring to Adam and Eve) text omits "image", the fact that "image" and "likeness" indicate two similar concepts but different. I think "image" means human nature able to conceive the evil, so the suffering too; instead "likeness" denotes the inherited attributes of God as love, reason, etc. they are both still together. Hypothetically speaking, the man of the sixth day is a creature evolved from monkeys or some other thing, then over time, has developed the reason as we know it today, while Adam and Eve were created in the Garden of Eden, namely in a perfect reality, in which there was no concept of evil, so they were only a "likeness" of God. After that they were created, were expelled from Eden, only to find themselves in this situation, where perhaps, the man who was created in the image and likeness did not exist more because of a mass extinction caused by some natural catastrophe or by "something else"; or perhaps still he existed, and the descendants of Adam and Eve hybridazed this species, confirmed in Genesis 6:1,2,3,4, in which he says that the sons of God married the daughters of men (but may also be refers to the descendants of Cain, who turned away from God). The spirit of God will not dwell forever with the man because he also is flesh, living up to 120 years (mean that men of God who lived up to 900 years later live up to 120 years because of the fact that hybridising with the daughters of men they are "contaminated" at the genetic level, partially losing genes that enabled him to live a lot longer).

musica cloud a music social network 7/26/2015 3:23:48 AM United States #
musica cloud  a music social network

one pop mp3 download website for free

Forex Naked Truth 7/28/2015 9:48:44 AM United States #
Forex Naked Truth

[...] Trackback [...]

Marco 7/30/2015 5:35:02 PM United States #

Immediately after the tribulation of those days shall the sun be darkened, and the moon shall not give her light, and the stars shall fall from heaven, and the powers of the heavens shall be shaken: 30 And then shall appear the sign of the Son of man in heaven: and then shall all the tribes of the earth mourn, and they shall see the Son of man coming in the clouds of heaven with power and great glory. 31 And he shall send his angels with a great sound of a trumpet, and they shall gather together his elect from the four winds, from one end of heaven to the other.

Marco 8/2/2015 12:33:36 AM United States #

1Tim 1:1 Paul, an apostle of Christ Jesus by command of God our Savior and of Christ Jesus our hope, 1Tim 1:2 To Timothy, my true child in the faith: Grace, mercy, and peace from God the Father and Christ Jesus our Lord. 1Tim 1:3 As I urged you when I was going to Macedonia, remain at Ephesus so that you may charge certain persons not to teach any different doctrine, 1Tim 1:4 nor to devote themselves to myths and endless genealogies, which promote speculations rather than the stewardship from God that is by faith. 1Tim 1:5 The aim of our charge is love that issues from a pure heart and a good conscience and a sincere faith. 1Tim 1:6 Certain persons, by swerving from these, have wandered away into vain discussion, 1Tim 1:7 desiring to be teachers of the law, without understanding either what they are saying or the things about which they make confident assertions. 1Tim 1:8 Now we know that the law is good, if one uses it lawfully, 1Tim 1:9 understanding this, that the law is not laid down for the just but for the lawless and disobedient, for the ungodly and sinners, for the unholy and profane, for those who strike their fathers and mothers, for murderers, 1Tim 1:10 the sexually immoral, men who practice homosexuality, enslavers, liars, perjurers, and whatever else is contrary to sound doctrine, 1Tim 1:11 in accordance with the gospel of the glory of the blessed God with which I have been entrusted. 1Tim 1:12 I thank him who has given me strength, Christ Jesus our Lord, because he judged me faithful, appointing me to his service, 1Tim 1:13 though formerly I was a blasphemer, persecutor, and insolent opponent. But I received mercy because I had acted ignorantly in unbelief, 1Tim 1:14 and the grace of our Lord overflowed for me with the faith and love that are in Christ Jesus. 1Tim 1:15 The saying is trustworthy and deserving of full acceptance, that Christ Jesus came into the world to save sinners, of whom I am the foremost. 1Tim 1:16 But I received mercy for this reason, that in me, as the foremost, Jesus Christ might display his perfect patience as an example to those who were to believe in him for eternal life. 1Tim 1:17 To the King of the ages, immortal, invisible, the only God, be honor and glory forever and ever. Amen. 1Tim 1:18 This charge I entrust to you, Timothy, my child, in accordance with the prophecies previously made about you, that by them you may wage the good warfare, 1Tim 1:19 holding faith and a good conscience. By rejecting this, some have made shipwreck of their faith, 1Tim 1:20 among whom are Hymenaeus and Alexander, whom I have handed over to Satan that they may learn not to blaspheme.

agua bendita espectaculo 8/6/2015 5:53:12 PM United States #
agua bendita espectaculo