Contents tagged with .NET
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:
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!
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.
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.
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:
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!
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.
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.
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:
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.
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.
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.
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.
Create the Controller
Let’s now create the controller to instantiate an instance of the MusicGenreViewModel class and pass that instance to the view.
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.
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.
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.
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.
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.
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.
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.
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.
That is pretty much all there is to binding to a true/false value using MVC.
Script for Toggling
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’.
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.
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.
If you are in the Nashville, TN area, I hope you will join me at the Nashville .NET User Group http://nashdotnet.org/ for a seminar entitled "Best Practices for Flexible Code".
Creating applications that are flexible and maintainable means thinking about application development a little differently. You need to adopt good object-oriented techniques in order to create software that can truly adapt to a changing development environment. In this seminar you will see many examples of tips and tricks that will help you keep your software running for many years to come. You will see real-world examples of extension methods, faster reflection, string handling, generics, using XML, wrapper classes, dependency injection, configuration and exception management. You will walk away with a code that you can use in your applications right away.
So, come on out at (http://nashdotnet.org/) at 6pm on Thursday, April 10th, 2014.
Hope to see you there!
Before beginning any application development consider implementing programming and database standards with your team. Using development standards allows all programmers to know what is expected of them and how to create new applications from scratch. Standards help developers move from one project to another without having to learn a different style of programming because it was created by another programmer.
There are many reasons programming standards are created. Many years ago when mainframes were in vogue, every shop had programming standards. In fact, they used to teach programming standards in college. Now, standards are all but forgotten or just never learned by the younger generation. Microsoft does have a set of programming standards for C# and Visual Basic. These are an excellent place to start, and I would like to encourage all programmers today to adopt some sort of standards as an important first step in application development.
Creating standards does not limit your creativity as most programmers seem to think. Programming standards help you focus your creativity where it is really needed. You concentrate on the business problem you are trying to solve, instead of having to always think about what name to give a method or variable. As a corollary, consider the Windows and Mac operating environments where most programs written have a consistent look and feel. This is why users like using Windows or Macs, because they do not have to learn everything about how a new program works. They already know how to use most of the features in each program. Utilizing standards in your programming, you keep the programmer’s “look and feel” consistent. You will spend less time figuring out what the variables are or how many indents a programmer used, and you can focus more on the logic of the program.
The use of standards lead to reduced maintenance costs as well, due to consistency in each program. You can move from one project to another very easily, even one someone else wrote, and immediately read and understand the code. Programming standards help programmers create a consistent structure, code style, variable names, and methods names within all applications. Standards also help programmers create code that is unambiguous, easy to read, and easy to maintain by other developers.
The standards documents you should have in place at your shop are Visual Studio Setup, C# or Visual Basic Programming Standards, SQL Server Object Naming Standards and Database Development Standards. The rules set forth in these documents are guidelines, so feel free to modify these to suit your own organizations’ needs.
- The Visual Studio Setup document is used to ensure each programmer configures their Visual Studio the same as everyone else in the shop. Especially important is the Tab setting so everyone uses the same tab indent. If different programmers use different tabs and they get changed, this can wreak havoc on your source control.
- The C# or Visual Basic Programming Standards document will set forth variable and method naming, class naming, file naming, control naming and many other standards.
- The SQL Server Object Naming Standards document describes how to name tables, stored procedures, views, and other database objects. You should also describe how SQL keywords and functions in your SQL statements are cased.
- The Database Development Standards document describes your database design philosophy. Your philosophy may include things such as how you create primary keys, the use of clustered indexes, standard fields for each table, how to handle concurrency, and whether or not to use dynamic SQL or stored procedures.
You can find examples of all of these standards documents at my website: http://www.pdsa.com/download/StandardsDocuments.zip
We have definitely found that having programming standards in place at our shop has been a positive thing. I hope they work equally as well for you.
I have just published a new course on www.pluralsight.com! Check it out!
WPF For the Visual Basic Programmer
Visual Basic Programmers are still in demand. Upgrade your skills by learning XAML and WPF. This course is specifically designed for the Visual Basic programmer and will get you up to speed quickly with WPF. In Part 1 you will learn the correct way to design WPF windows, how to use styles and all the most commonly used controls for business applications. You will gain a good knowledge of data binding and how to use the various list controls in WPF.
I am pleased to announce that I have released two more courses on Pluralsight.com.
How to Start and Run a Consulting Business
Have you ever wanted to break out of the corporate life and be your own boss? Many people have this dream. In this course you will learn what it takes to start and be successful in your own consulting business. Throughout this video you will learn how to determine what your company should look like, how to manage your money wisely, how to get and keep clients, how best to survive the ups and downs of the economy and how to create an exit strategy. Your instructor has been running his own successful business for over 22 years and shares his valuable insight so you too can be a success!
Module 1: Hanging Your Shingle
Module 2: Money Matters
Module 3: How to Get and Keep Clients (or Marketing 101)
Module 4: How To Survive the Ups and Downs
Module 5: Creating an Exit Strategy
WPF for the Business Programmer
There are so many cool things you can do with WPF that would be impossible or very difficult with Windows Forms. In this video you will see some creative ways to use the WPF List Box. Some screens that you can use right away in your business applications will be presented. You will learn some unique ways to put together user controls to create unique shapes. Finally you will create a shell application to make your WPF application look like Windows 8. This course goes way beyond the basics of WPF to give you some unique insights on how to create business applications.
Module 1: The Flexible WPF List Box
Module 2: More Fun with the WPF List Box
Module 3: Develop Business Application Screens in WPF
Module 4: Create WPF Shapes with Text
Module 5: Creating a Windows 8 Shell in WPF
And of course, my first course is:
The Many Approaches to XML Processing in .NET Applications
Did you know that you can use XML instead of a SQL database for applications? Did you know there is LINQ to XML that allows you to process XML documents quickly and efficiently? If the answer is no to either of these two questions, then you need to watch this course. XML files are very common in today's programming world. You will most likely need to read files, write files and query XML within your applications. .NET provides a rich set of XML processing classes that you can use to perform all these functions. C# allows you to easily create, read and query XML files using XPath, LINQ to XML and other methods. In this course you will learn to read and write XML files using the various .NET classes. You will see some real-world uses of XML files in applications.
Module 1: What is this XML Thing Anyway?
Module 2: A Myriad of Methods to Read XML
Module 3: 16 Ways to Write XML Documents
Module 4: Real World Uses of XML
Module 5: LINQ to XML Step-by-Step
Module 6: Use XML: An Alternative to SQL
Go to www.pluralsight.com and sign up today and start learning!