Paul Sheriff's Blog for the Real World

This blog is to share my tips and tricks garnered over 25+ years in the IT industry

  • Additions on a Bootstrap Panel

    Additions on a Bootstrap Panel

    The Bootstrap panel classes allow you to create a bordered area on your web page. The panel classes give you a title area, a body area and a footer area. Most designers add buttons within the footer area to perform different actions on the information within the panel. Sometimes they add additional drop-downs or buttons within the body of the panel to reload the data or take action. While these work, sometimes you don’t want to take up that real estate with those actions. Instead you can use the title area of the panel for these additions. This blog post will show you how to accomplish this.

    Add a Reload Button

    The first example you will learn is how to add on a ‘reload’ button to the right-most area of the panel as seen in Figure 1.

    Figure 1: Add a Reload Button to the Panel’s Title area

    To add this new button to the title, create an anchor tag within the <h1> or whatever HTML element you use for the panel title. I added a glyph from Bootstrap and the word “Reload” within this anchor tag. I then added one additional class called panel-right to that anchor tag as shown in the following code.

    <div class="panel panel-primary">

      <div class="panel-heading">

        <h1 class="panel-title">

          <span class="glyphicon glyphicon-music">

          </span>

            &nbsp;CountryMusic

          <a href="#"

             class="panel-right glyphicon glyphicon-random">

             &nbsp;Reload

          </a>

        </h1>

      </div>

      <div class="panel-body">

         // Other HTML here

      </div>

    </div>

    The “panel-right” class is very simple and is responsible for the look and feel of the button on the right side of the panel. You first add a border around the button and modify the border radius. Add a margin-top to position the button in the correct location. Modify the padding and font-size as appropriate. Finally set the float to right so the button stays on the right side of the panel. Turn off all text-decoration on the anchor tag so you don’t get any underline on the button. All of the styles shown below will be placed into a .CSS file that you can then add to any page where you wish to use panel additions.

    .panel-right {

      border: 0.05em solid lightgray;

      border-radius: 0.25em 0.25em;

      margin-top: -0.2em;

      padding: 0.3em;

      font-size: 0.9em;

      float: right;

    }

     

      .panel-title a,

      .panel-title a:active,

      .panel-title a:visited {

        text-decoration: none;

      }

    Drop Down in Panel

    Another example of an addition you could add to a panel would be a drop-down selector as shown in Figure 2.

    Figure 2: Adding a Drop-Down in the Panel Title Area

    Adding a drop-down is a little different from a simple button as shown in the last example. You need a little more room within the panel-title so instead of an <h1> element use a <div>. This gives just a little more room within the panel-title. In addition you can’t nest a div tag within an h1, so we are forced to use this outer div element. Within the <div> element, place another <div> to contain the Bootstrap class ‘dropdown’ and the panel-right class. Create your normal drop-down button as shown in the example that follows:

    <div class="panel panel-primary">

      <div class="panel-heading">

        <div class="panel-title">

          <span class="glyphicon glyphicon-music">

          </span>

          &nbsp;

          <span id="genre">Country Music</span>

          <div class="dropdown panel-right">

            <button class="btn btn-success"

                    id="selectButton"

                    data-toggle="dropdown">

              Change Genre&nbsp;

              <span class="caret"></span>

            </button>

            <ul class="dropdown-menu" id="ulGenres">

              <li><a href="#">Jazz</a></li>

              <li><a href="#">Country</a></li>

              <li><a href="#">Rock</a></li>

            </ul>

          </div>

        </div>

      </div>

      <div class="panel-body">

         // Other HTML here

      </div>

    </div>

    The style you use for the panel-right is a little different from the previous example. You need a different margin-top and you need to turn off the border. So on this page you will include the .CSS file you created with the previous styles, then after this <link> you add the following styles to override the ones in the .CSS file.

    <link href="~/Content/pdsa-panel-additions.css"

          rel="stylesheet" />

     

    <style>

      .panel-right {

        border: none;

        margin-top: -0.65em;

      }

    </style>

    When you select an item from the drop-down selector you should change the title on the panel. You can use a little jQuery code to accomplish this. Add the following script at the bottom of your page to modify the text within the panel title when the user clicks on an item in the drop-down selector.

    <script>

      $(document).ready(function () {

        $("#ulGenres li a").on("click", function () {

          var text = $(this).text();

          $("#genre").text(text + ' Music');

        });

      });

    </script>

    Summary

    In this blog post you learned how to add some additions to the Bootstrap panel classes. Using the right side of the panel is a great way to allow your user to perform actions within the panel without taking up valuable real estate within the panel itself.

    Read more...

  • A Simple Bootstrap Radio Button for MVC

    A Simple Bootstrap Radio Button for MVC

    In a previous blog post I talked about a simple push button style of radio buttones. This sample push button style can be applied to radio buttons too. This style of button is very easy to do with just some built-in Bootstrap styles and a little extra CSS.

    Simple Radio Button

    As a way to get a better looking radio button, you can wrap a radio button into a button as shown in Figure 1. What is nice about this style of radio button is it wraps the label together with the radio button. In addition, on a mobile device it is much easier to press as the whole button area is clickable.

    Figure 1: Radio buttons wrapped into a button

    To create these radio buttones you wrap the radio button within the normal Bootstrap class “checkbox”. You then add a label element with the classes “btn btn-default” around the radio button as shown in the following code:

    @using (Html.BeginForm())

    {

      <div class="well well-sm">

        <div class="form-group">

          <div class="radio">

            <label class="btn btn-default">

              @Html.RadioButton("gender", "Male",

                                true, new { id = "IsMale" })

              Male

            </label>

          </div>

        </div>

        <div class="form-group">

          <div class="radio">

            <label class="btn btn-default">

              @Html.RadioButton("gender", "Female",

                                new { id = "IsFemale" })

              Female

            </label>

          </div>

        </div>

      </div>

    }

    To make it appear correctly, you have to add the following CSS to align the radio button and the text correctly within the button. That is all there is to it!

    <style>

      .radio .btn,

      .radio-inline .btn {

        padding-left: 2em;

        min-width: 7em;

      }

     

      .radio label,

      .radio-inline label {

        text-align: left;

      }

    </style>

    Summary

    Creating better looking controls for your web page is sometimes very simple and just involves combing a couple of elements together along with a tiny bit of CSS.

    Read more...

  • A Simple Bootstrap Check Box for MVC

    A Simple Bootstrap Check Box for MVC

    I really enjoy working with Bootstrap and extending the styles to match what my customers want. Recently my customer wanted a simple push button style of check box and radio buttons. This turned out to be very easy to accomplish using the built-in Bootstrap styles and just a little extra CSS.

     

    Simple Check Box

    As a way to get a better looking check box, you can wrap a check box into a button as shown in Figure 1. What is nice about this style of check box is it really puts the label together with the check box. In addition, on a mobile device it is much easier to hit as the whole button area is clickable.

    Figure 1: Check boxes wrapped into a button

    To create these check boxes you simply have to wrap the check box within the normal Bootstrap class “checkbox”. You then add a label element with the classes “btn btn-default” around the check box as shown in the following code:

    @using (Html.BeginForm())

    {

      <div class="well well-sm">

        <div class="form-group">

          <div class="checkbox">

            <label class="btn btn-default">

              @Html.CheckBox("IsJazz")

              Jazz

            </label>

          </div>

        </div>

        <div class="form-group">

          <div class="checkbox">

            <label class="btn btn-default">

              @Html.CheckBox("IsCountry")

              Country

            </label>

          </div>

        </div>

        <div class="form-group">

          <div class="checkbox">

            <label class="btn btn-default">

              @Html.CheckBox("IsRock")

              Rock

            </label>

          </div>

        </div>

      </div>

    }

    To make it appear correctly, you have to add the following CSS to align the check box and the text correctly within the button. That is all there is to it!

    <style>

      .checkbox .btn,

      .checkbox-inline .btn {

        padding-left: 2em;

        min-width: 7em;

      }

     

      .checkbox label,

      .checkbox-inline label {

        text-align: left;

      }

    </style>

    Summary

    Creating better looking controls for your web page is sometimes very simple and just involves combing a couple of elements together along with a tiny bit of CSS.

    Read more...

  • A Simple Bootstrap Radio Button for Web Forms

    A Simple Bootstrap Radio Button for Web Forms

    In a previous post I talked about creating a push-button style of radio button for MVC. This blog post will show how to create the same push-button radio button using Web Forms. There are only a few minor differences in the CSS and, of course, in the use of a Web Forms server control.

    Simple Radio Button

    As a way to get a better looking radio button, you can wrap a radio button into a button as shown in Figure 1. What is nice about this style of radio button is it wraps the label together with the radio button. In addition, on a mobile device it is much easier to press as the whole button area is clickable.

    Figure 1: Radio buttons wrapped into a button

    To create these radio buttones you wrap the radio button within the normal Bootstrap class “checkbox”. You then add a label element with the classes “btn btn-default” around the radio button as shown in the following code:

    <div class="form-group">

      <div class="radio">

        <label class="btn btn-default">

          <asp:RadioButton ID="IsMale" runat="server"

            GroupName="gender"

            Checked="true"

            Text="Male" />

        </label>

      </div>

    </div>

    <div class="form-group">

      <div class="radio">

        <label class="btn btn-default">

          <asp:RadioButton ID="IsFemale" runat="server"

            GroupName="gender"

            Text="Female" />

        </label>

      </div>

    </div>

    To make it appear correctly, you have to add the following CSS to align the radio button and the text correctly within the button. That is all there is to it!

    <style>

      .radio .btn,

      .radio-inline .btn {

        padding-left: 2em;

        min-width: 7em;

      }

     

      .radio label,

      .radio-inline label {

        text-align: left;

        padding-left: 0.5em;

      }

    </style>

    Summary

    Creating better looking controls for your web page is sometimes very simple and just involves combing a couple of elements together along with a tiny bit of CSS.

    Read more...

  • A Simple Bootstrap Check Box for Web Forms

    A Simple Bootstrap Check Box for Web Forms

    In a previous post I talked about creating a push-button style of check box for MVC. This blog post will show how to create the same push-button check box using Web Forms. There are only a few minor differences in the CSS and, of course, in the use of a Web Forms server control.

    Simple Check Box

    As a way to get a better looking check box, you can wrap a check box into a button as shown in Figure 1. What is nice about this style of check box is it really puts the label together with the check box. In addition, on a mobile device it is much easier to hit as the whole button area is clickable.

    Figure 1: Check boxes wrapped into a button

    To create these check boxes you simply have to wrap the check box within the normal Bootstrap class “checkbox”. You then add a label element with the classes “btn btn-default” around the check box as shown in the following code:

    <div class="form-group">

      <div class="checkbox">

        <label class="btn btn-default">

          <asp:CheckBox ID="IsJazz" runat="server"

                        Text="Jazz" />

        </label>

      </div>

    </div>

    <div class="form-group">

      <div class="checkbox">

        <label class="btn btn-default">

          <asp:CheckBox ID="IsCountry" runat="server"

                        Text="Country" />

        </label>

      </div>

    </div>

    <div class="form-group">

      <div class="checkbox">

        <label class="btn btn-default">

          <asp:CheckBox ID="IsRock" runat="server"

                        Text="Rock" />

        </label>

      </div>

    </div>

    To make it appear correctly, you have to add the following CSS to align the check box and the text correctly within the button. That is all there is to it!

    <style>

      .checkbox .btn,

      .checkbox-inline .btn {

        padding-left: 2em;

        min-width: 8em;

      }

     

      .checkbox label,

      .checkbox-inline label {

        text-align: left;

        padding-left: 0.5em;

      }

    </style>

    Summary

    Creating better looking controls for your web page is sometimes very simple and just involves combing a couple of elements together along with a tiny bit of CSS.

    Read more...

  • Bind Custom Radio Buttons to Integer Data

    Bind Custom Radio Buttons to Integer Data

    In the last blog post I showed you how to bind radio buttons to a boolean value. In this blog post we will look at how to bind to integer values. In certain business applications you might have the user select a single value from a list of items coming from a database. You want to display these options as radio buttons and then retrieve the value the user selects.

    Create List of Radio Buttons

    If you look at Figure 1 you see a row of radio buttons using the custom look I created a few blog posts ago. This set of radio buttons comes from a collection of MusicGenre objects. Each MusicGenre class contains a GenreId and Genre property. GenreId is an integer value that represents the primary key. Genre is the string value such as ‘Jazz’, ‘Rock’, ‘Blues’, etc.

    Figure 1: A list of Radio Buttons

    The MusicGenre Entity Class

    To create the list of radio buttons in Figure 1, you first need a MusicGenre class as shown in the listing below:

    public class MusicGenre

    {

      public MusicGenre()

      {

        GenreId = 0;

        Genre = string.Empty;

      }

     

      public MusicGenre(int id, string genre)

      {

        GenreId = id;

        Genre = genre;

      }

     

      public int GenreId { get; set; }

      public string Genre {get;set;}

    }

    Create a Manager Class

    Next you create a “Manager” class to create the collection of MusicGenre objects. In this blog post you will use some mock data, but you could replace this with data from a real database table.

    public partial class MusicGenreManager

    {

      public MusicGenreManager()

      {

        Genres = new List<MusicGenre>();

        LoadAllMock();

      }

     

      public List<MusicGenre> Genres { get; set; }

     

      protected void LoadAllMock()

      {

        Genres.Add(new MusicGenre(1, "Jazz"));

        Genres.Add(new MusicGenre(2, "Country"));

        Genres.Add(new MusicGenre(3, "Rock"));

        Genres.Add(new MusicGenre(4, "Blues"));

        Genres.Add(new MusicGenre(5, "Alternative Rock"));

      } 

    }

    Create a View Model

    Now that you have these two classes created, create a View Model class that you can use from the Controller in our MVC application. This View Model class simply uses the two previous classes to populate a ‘Genres’ property that is a generic list of MusicGenre objects. We will also create one additional property in the View Model class to which to bind the selected genre id.

    public class MusicGenreViewModel

    {

      public MusicGenreViewModel()

      {

        Genres = new List<MusicGenre>();

        LoadGenres();

      }

     

      public List<MusicGenre> Genres { get; set; }

     

      public int SelectedId { get; set; }

     

      public void LoadGenres()

      {

        MusicGenreManager mgr = new MusicGenreManager();

     

        // Get list of Music Genres

        Genres = mgr.Genres;

      }

    }

    Create a View

    Create a .cshtml view page that will use the MusicGenreViewModel class that holds the list of MusicGenre objects. At the top of your view add the @model statement to specify you will be using the view model class. I added a little styling to provide some separation between each of the radio buttons.

    @model BootstrapRadio2.MusicGenreViewModel

     

    @{

      ViewBag.Title = "Data-Driven Radio Buttons";

    }

     

    <style>

      .pdsa-radiobutton {

        margin-right: .5em;

        text-align: left;

      }

    </style>

    Next you use the BeginForm statement to wrap all of the radio buttons and a submit button within a <form> tag. Notice that the RadioButtonFor() helper is binding to the SelectedId property in the View Model. If you select a radio button on the form and click the submit button, the GenreId from the 2nd parameter to the RadioButtonFor() helper is moved into the SelectedId property.

    @using (Html.BeginForm())

    {

      <div class="well well-sm">

        <h3>Data-Driven Radio Buttons</h3>

        <div class="form-group">

          <div class="btn-group" data-toggle="buttons" id="genre">

            @foreach (var item in Model.Genres)

            {

              <label class="pdsa-radiobutton btn btn-primary">

                <span class="glyphicon glyphicon-unchecked">

                </span>

                @Html.RadioButtonFor(m => m.SelectedId,

                                     item.GenreId,

                                     new { id = item.GenreId })

                @item.Genre

              </label>

            }

          </div>

        </div>

        <div class="form-group">

          <button type="submit"

                  class="btn btn-success">Submit</button>

        </div>

      </div>

    }

    Create the Controller

    Let’s now create the controller to instantiate an instance of the MusicGenreViewModel class and pass that instance to the view.

    public ActionResult Radio07()

    {

      MusicGenreViewModel vm = new MusicGenreViewModel();

     

      return View(vm);

    }

    Retrieve the Value Selected

    Once you select a radio button and click on the Submit button you post back to another controller action as shown below. The SelectedId property is automatically bound to the view model class. All you have to do to retrieve the appropriate MusicGenre object is loop through the list of MusicGenre objects and find where the selected id matched the GenreId. You can accomplish this with the Find() method on the collection class.

    [HttpPost]

    public ActionResult Radio07(MusicGenreViewModel vm)

    {

      MusicGenre entity;

     

      entity = vm.Genres.Find(g => g.GenreId == vm.SelectedId);

     

      System.Diagnostics.Debugger.Break();

     

      return View(vm);

    }

    Summary

    This blog post showed you how to bind a set of radio buttons to a set of objects with a unique ID. This simulates using data coming from a database table with an integer primary key.

    Read more...

  • Bind Custom Radio Buttons to True/False Property

    Bind Custom Radio Buttons to True/False Property

    In the last blog post I showed you how to create a different look and feel for radio buttons. We used the button groups and glyph icons from bootstrap to build this different look. Now let’s bind these radio buttons to a single boolean property in a class.

    Let’s say you have a Product class that has an IsDiscontinued property that you would like a user to select between an “Active” and a “Discontinued” product. You might design the screen to look like Figure 1.

    Figure 1: Choose between two Boolean states.

    To build this screen you first create your Product class. The code below shows an example Product class. The IsDiscontinued property is the property you bind to.

    namespace BootstrapRadio2

    {

      public partial class Product

      {

        public int ProductId { get; set; }

        public string ProductName { get; set; }

        public decimal Price { get; set; }

        public bool IsDiscontinued { get; set; }

      }

    }

    Create your cshtml view and specify the name of the model to use at the top of the file. I also added a little styling to a class called pdsa-radiobutton that puts a little spacing between the two radio buttons.

    @model BootstrapRadio2.Product

     

    @{

      ViewBag.Title = "Get/Set Values from Model";

    }

     

    <style>

      .pdsa-radiobutton {

        margin-right: .5em;

        text-align: left;

      }

    </style>

    Build your view using the Html.BeginForm() helper to emit a <form> tag. Create a “form-group” into which you put a “btn-group”. If you are not familiar with button groups in Bootstrap you should look at www.getbootstrap.com for more information. The <label>, and <span> tags should be self-explanatory, especially if you read my first blog post on creating these types of radio buttons.

    The next item you need is to bind the IsDiscontinued property to an HTML radio button. You use the @HtmlRadioButtonFor() helper to do this binding. The first parameter to this helper is the expression to bind to the product in the model. The second parameter is the value to return to the model if this button is chosen. The third parameter is a collection of other attributes you wish to be emitted into the HTML. Lastly we need a submit button to post the data back to our controller.

    @using (Html.BeginForm())

    {

      <h3>Get/Set Values from Model</h3>

      <div class="form-group">

        <div class="btn-group" data-toggle="buttons" id="product">

          <label class="pdsa-radiobutton btn btn-primary">

            <span class="glyphicon glyphicon-unchecked"></span>

            @Html.RadioButtonFor(m => m.IsDiscontinued, "false",

                new { id = "IsActive" }) Is Active?

          </label>

          <label class="pdsa-radiobutton btn btn-primary">

            <span class="glyphicon glyphicon-unchecked"></span>

            @Html.RadioButtonFor(m => m.IsDiscontinued, "true",

                new { id = "IsDiscontinued" }) Is Discontinued?

          </label>

        </div>

      </div>

      <div class="form-group">

        <button type="submit"

                class="btn btn-success">Submit</button>

      </div>

    }

    The Controller

    There are two methods you add to the controller for this view. First is the GET method, defined here as “Radio06”. This method creates a new instance of the Product class and sets the IsDiscontinued property to either a true or false. Normally this data would be coming from a database, but this mock data illustrates how binding selects the default button chosen when the view renders.

    public ActionResult Radio06()

    {    

      Product entity = new Product();

     

      entity.IsDiscontinued = true;

     

      return View(entity);

    }

    The second method to add the controller is called when the user clicks on the submit button on the screen. The ‘value’ attribute of the button selected at the time of the submit will be automatically assigned to the instance of the Product class, named ‘entity’ in this sample. Within this method I put a Debugger.Break() so you can inspect the properties of the entity variable to see the IsDiscontinued property and verify that it is set to the correct value.

    [HttpPost]

    public ActionResult Radio06(Product entity)

    {

      System.Diagnostics.Debugger.Break();

     

      return View(entity);

    }

    That is pretty much all there is to binding to a true/false value using MVC.

    Script for Toggling

    The jQuery and JavaScript used on this page is the same as what I presented in my last blog post. The only difference is I added code that runs when the page is loaded. This code will select the radio button that is “checked” and ensure that the proper glyph is rendered on the button. All radio buttons on your page should have the ‘glyphicon-unchecked’ in the class attribute. This class attribute is changed on the selected radio button by the code that runs when the page is loaded.

    @section scripts

    {

      <script>

        $(document).ready(function () {

          // Detect radio button that is checked and toggle glyph

          $("input[type='radio']:checked").prev()

            .removeClass('glyphicon-unchecked')

            .addClass('glyphicon-record');

        });

      </script>

    }

    The jQuery code that runs when the page is loaded will first select any radio buttons that are checked. You then need to move the previous element in the DOM which will be the <span> tag with the glyph icon to change. You remove the ‘glyphicon-unchecked and add the class ‘glyphicon-record’.

    Summary

    In this blog post you saw how to take our custom radio buttons and bind them to a true/false property on a class. In addition you learned how to take the selected radio button and toggle the glyph icon when the page is loaded.

    Read more...

  • Creating Radio Buttons using Bootstrap and MVC

    As I previously published, the normal HTML check boxes and radio buttons just do not look good in bootstrap. Yes, bootstrap has a CSS class that will attempt to at least let render a radio button consistently across browsers, but it still is just the default HTML look. In addition, trying to hit a radio button on a mobile phone can sometimes be a little challenging.

    Read more...

  • Bind Check Boxes to a Collection in MVC

    In my last two blog posts I showed you how to use the bootstrap ‘btn-group’ class to create check boxes that are a little nicer looking and easier to use on a mobile device. In addition I showed you how to bind check boxes to individual properties on an entity class. In this blog post you will learn how to create a set of check boxes from a collection of entity classes. You will also learn how to retrieve which check boxes were checked by the user and update the appropriate entity class in the collection with these values.

    Figure 1: Create checkboxes from a collection of entity classes

    Music Genre Class

    Create a class for each music genre you wish to display in the check boxes shown in Figure 1. For each genre of music you need a unique id, the string to display and a boolean value for whether or not it was selected. The MusiGener class, shown below contains the appropriate properties along with a constructor to create a MusicGenre instance from values passed to the constructor.

    public class MusicGenre

    {

      public int GenreId { get; set; }

      public string Genre {get;set;}

      public bool IsSelected { get; set; }

     

      // Constructor to create new MusicGenre object

      public MusicGenre(int id, string genre)

      {

        GenreId = id;

        Genre = genre;

        IsSelected = false;

      }

    }

    Create View Model Class

    Using a View Model class from your controller is an excellent way to get reusability across different UI technologies. A view model is usable from Web Forms, WPF, Windows Phone and even Windows Forms applications. You can also unit test view model classes easily. Create a view model class that builds a collection of musical genres from a database table (or any other data store). Create an instance of this view model in your controller and use this instance as the @model in your .cshtml file.

    public class MusicGenreViewModel

    {

      public MusicGenreViewModel()

      {

        LoadGenresMock();

      }

     

      public List<MusicGenre> Genres { get; set; }

     

      public void LoadGenresMock()

      {

        // Create mock list of data

        // Normally you would load this data from a database

        Genres = new List<MusicGenre>();

         

        Genres.Add(new MusicGenre(1, "Jazz"));

        Genres.Add(new MusicGenre(2, "Country"));

        Genres.Add(new MusicGenre(3, "Rock"));

        Genres.Add(new MusicGenre(4, "Blues"));

        Genres.Add(new MusicGenre(5, "Alternative Rock"));

      }

    }

    In the view model class, named MusicGenreViewModel, I created a method called LoadGenresMock(). Normally you would call your data layer to get this list of musical genres from a database table, but for this example, I just needed some data to build my list of check boxes, so I hard-coded the values.

    Bind to Collection of Musical Genres

    Once you have your collection of musical genres loaded into your view model, create an instance of the view model class in your controller. You can optionally set the IsSelected property of any specific genres to true in order to have those check boxes “checked” when the screen first displays. Pass the view model to your View, named CollectionTest, as shown in the code below.

    public ActionResult CollectionTest()

    {

      MusicGenreViewModel vm = new MusicGenreViewModel();

     

      vm.Genres.Find(g => g.Genre == "Jazz").IsSelected = true;

      vm.Genres.Find(g => g.Genre == "Rock").IsSelected = true;

     

      return View(vm);

    }

    View for Collection of Check Boxes

    Create a new view in an MVC project, named CollectionTest, and add the @model to use the view model class. To build the list of check boxes you will need to loop through the Genres collection. Each time through the loop is where you need to create each check box from the MusicGenre class. However, since you can’t have two @model statements in a view, create a partial view that you can pass each instance of the MusicGenre class to. The code for the CollectionTest view is shown below:

    @model BootstrapCheckBoxes3.MusicGenreViewModel

     

    @using (Html.BeginForm())

    {

      <div class="well">

        <h3>Checkboxes Built from a Collection</h3>

        <div class="row">

          <div class="col-md-8">

            <div class="btn-group" data-toggle="buttons">

              @foreach (var item in @Model.Genres)

              {

                Html.RenderPartial("_CollectionTestGenre", item);

              }

            </div>

          </div>

        </div>

        <div class="row">

          <div class="col-md-12">

            <button class="btn btn-success"

                    type="submit">Submit

            </button>

          </div>

        </div>

      </div>

    }

    Partial View

    The partial view, called _CollectionTestGenre, is where you create each check box. Notice that you have a @model in this partial view that is the instance passed in of the MusicGenre class from the main view. In this partial view is where you use the CheckBoxFor() helper method to create the check box. Notice that you will set the ‘value’ attribute of each check box to the GenreId. You will use this value when the data is posted back.

    @model BootstrapCheckBoxes2.MusicGenre

     

    <label class="pdsa-checkbox-group btn btn-primary">

      <span class="glyphicon glyphicon-unchecked"></span>

      @Html.CheckBoxFor(m => m.IsSelected,

                        new { value = @Model.GenreId })

      @Html.LabelFor(x => x.Genre, Model.Genre)

    </label>

    Posting Collection Back to Controller

    Once you have checked and unchecked any of the check boxes, click on the Submit button to post back the form data. As mentioned earlier the ‘value’ attribute of each check box is set to the GenreId. When you check a check box on the form, the value attribute is what is posted back for that check box. All unchecked check boxes will have the value ‘false’ posted back.

    The name of each check box is set to IsSelected, so if you call Request.Form[“IsSelected”] you will get back a comma-delimited list of all check boxes that have been selected and not selected. If you check 3 of the check boxes, you get back a string that looks like the following: "1,false,2,false,3,false,false,false". All you have to do is convert this comma-delimited list to an array and find all the numeric values. Take each numeric value and place into an integer array. From this integer array set the appropriate Genre’s IsSelected property to true if the integer value is the same as the GenreId.

    As you will most likely be using different check boxes on different web pages, create a generic method to perform this conversion from a string to an integer array. I created a WebCommon class and created a method called RequestSelectionToList(). This method, shown below, uses the Split() method of the string class to separate each value from the comma-delimited list and create an array. The array is then converted to a generic list of string values using the ToList() method. It then loops through this list of string values looking for integer values. For each integer value it finds, it adds that value to a generic integer list.

    public class WebCommon

    {

      public static List<int> RequestSelectionToList(

        string values)

      {

        List<int> ret = new List<int>();

        List<string> selected = values.Split(',').ToList();

        int value = 0;

     

        // Loop through selected items looking for integer values

        foreach (string item in selected)

        {

          if (int.TryParse(item, out value))

          {

            ret.Add(value);

          }

        }

     

        return ret;

      }

    }

    Once you have this class created and this method to extract the list of integer values from the Request.Form[“IsSelected”], you can now use it in the controller. Create a method in your controller to respond to the HttpPost. Write the following code in your controller to set the appropriate IsSelected properties in the Genres collection.

    [HttpPost]

    public ActionResult CollectionTest(MusicGenreViewModel vm)

    {

      List<int> selected = WebCommon.

        RequestSelectionToList(Request.Form["IsSelected"]);

     

      // Loop through selected items looking for integer values

      foreach (int item in selected)

      {

        // Set the IsSelected property on the appropriate GenreId

        vm.Genres.Find(g => g.GenreId == item).IsSelected = true;

      }

     

      return View(vm);

    }

    Summary

    Working with check boxes in a collection takes a little more work than just setting individual boolean values in a simple entity class. If you set the ‘value’ attribute to the unique id for each of your check boxes, you will be able to retrieve the unique id from the Request.Form collection. From this you can set your appropriate boolean property to true for each check box selected by your user.

    Read more...