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

11. mei 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

image

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 http://taitems.github.io/UX-Lab/ToggleSwitch/ which had some errors in my opinion.

image 

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 http://taitems.github.io/UX-Lab/ToggleSwitch/ 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() {
alert("Changed!!");
});
});

I attached a sample MVC application as well as the JQuery.UI.ToggleSwitch plugin.

ToggleSampleMVC4.zip (771,1 KB)
jquery.ui.toggleswitch.zip (1,73 KB)
Samual Frutiger 4-9-2013 03:46:53 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 11-9-2013 22:26:13 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 11-9-2013 22:27:03 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 24-9-2013 00:10:54 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 24-9-2013 23:22:40 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 26-9-2013 01:58:37 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 30-9-2013 19:30:36 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 4-10-2013 03:42:25 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 5-10-2013 02:00:20 United States #
Handmade Jewelry

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

Handmade Jewelry 5-10-2013 19:12:41 United States #
Handmade Jewelry

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

Copper Jewelry 6-10-2013 23:18:22 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 8-10-2013 03:07:11 United States #
Handmade Jewelry

I  as well  believe   thence , perfectly  pent  post! .

Handmade Jewelry 8-10-2013 22:02:41 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 9-10-2013 01:35:02 United States #
Dale Angle

Hey check this new project http://bit.ly/Bigbuun

Darrell Coran 9-10-2013 03:24:56 United States #
Darrell Coran

Hey check this new project http://projectalfa.ueuo.com/

Yuk Letterman 9-10-2013 05:03:00 United States #
Yuk Letterman

Best advices across internet http://projectalfa.ueuo.com/

Winifred Maes 9-10-2013 17:24:19 United States #
Winifred Maes

Hey check this new project http://projectalfa.ueuo.com/

Handmade Jewelry 11-10-2013 00:36:17 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 12-10-2013 16:51:41 United States #
energooszczedne

im glad to see this webpage

hareketli bayrak 12-10-2013 21:03:55 United States #
hareketli bayrak

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

Copper Jewelry 14-10-2013 02:40:35 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 19-10-2013 01:11:51 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 1-11-2013 22:33:16 United States #
Handmade Jewelry

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

Handmade Jewelry 3-11-2013 05:57:09 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 7-11-2013 14:19:11 United States #
Kathie Knop

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

Handmade Jewelry 11-11-2013 04:55:37 United States #
Handmade Jewelry

Dead written    topic matter, Truly enjoyed  reading through .

Eagle Safety Products 12-11-2013 08:12:27 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 12-11-2013 12:19:06 United States #
Demarcus Curts

The New IAPS Security Store: http://www.intl-alliance.com/store/

Welding Gas 14-11-2013 07:59:43 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 20-11-2013 23:40:09 United States #
Pat Bielefeld

This really answered my problem, thank you!

from this source 17-12-2013 13:52:19 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 20-12-2013 02:14:08 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 20-12-2013 09:11:24 United States #
home

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 17-1-2014 01:08:52 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=http://acidreflux.adsboards.com>acid reflux diet</a>

visit website 19-1-2014 09:56:19 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 6-2-2014 17:28:35 United States #
Shakita

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

Acheter liquide ecigarette 11-2-2014 21:36:25 United States #
Acheter liquide ecigarette

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

voyance tout de suite 12-2-2014 02:19:06 United States #
voyance tout de suite

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

ekonomia 17-2-2014 12:45:05 United States #
ekonomia

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

Keywords Jeet 18-2-2014 13:57:34 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 22-2-2014 00:03:30 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 https://vimeo.com/84827976

jewels 23-2-2014 14:18:27 United States #
jewels

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

jewels advice 23-2-2014 18:49:18 United States #
jewels advice

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

Kit 28-2-2014 22:54:53 United States #
Kit

You information has been of great help, nice work

Brandie 1-3-2014 23:28:47 United States #
Brandie

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

good 12-3-2014 06:13:26 United States #
good

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 14-3-2014 16:14:13 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 23-3-2014 06:38:22 United States #
teeth whitening

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

chatline 3-5-2014 02:51:13 United States #
chatline

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 4-5-2014 15:21:31 United States #
Solomon

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

Rodney 5-5-2014 19:05:09 United States #
Rodney

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 15-5-2014 18:10:55 United States #
other

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

Opal 25-5-2014 00:42:46 United States #
Opal

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 25-5-2014 16:14:24 United States #
Roman

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 5-6-2014 09:01:27 United States #
chat

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

Shaun Leslie 9-6-2014 19:16:33 United States #
Shaun Leslie

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

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

Given that I at first wrote above MBT sneakers at <strong><a href="incaltaminte-mopiel.ro/.../category&path=18_46"; 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 29-4-2015 04:30:07 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 16-5-2015 12:33:59 United States #
��C

merci pour ces informations

Candance Entz 5-6-2015 01:04:22 United States #
Candance Entz

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

Pearline Ringhouse 10-6-2015 01:39:41 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 blogengine.net. Is there a way I can import all my wordpress posts into it? Any kind of help would be greatly appreciated!

Velvet Caroway 10-6-2015 01:41:19 United States #
Velvet Caroway

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

Roberto Heisey 2-7-2015 13:21:38 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 22-7-2015 04:20:59 United States #
Marco

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 26-7-2015 03:23:48 United States #
musica cloud  a music social network

one pop mp3 download website for free

Forex Naked Truth 28-7-2015 09:48:44 United States #
Forex Naked Truth

[...] Trackback [...]

Marco 30-7-2015 17:35:02 United States #
Marco

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 2-8-2015 00:33:36 United States #
Marco

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 6-8-2015 17:53:12 United States #
agua bendita espectaculo