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

  • 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...

  • Bind Check Boxes in MVC

    After the last post on how to create check boxes that use the bootstrap “btn-group” to modify the look and feel of check boxes, I thought it would be good to show how to bind these check boxes using MVC. After all, you will most likely need to display check boxes based on data from a table.

    Figure 1: Check boxes should be bound to an entity class

    Musical Tastes Entity Class

    The first step is to have an entity (or model) class that contains the appropriate properties to bind to these check boxes. Below is a class I called MusicalTastes that simply has three Boolean properties that correspond to the three check boxes on the screen shown in Figure 1.

    public class MusicalTastes

    {

      public bool IsJazz { get; set; }

      public bool IsCountry { get; set; }

      public bool IsRock { get; set; }

    }

    View for Musical Tastes

    Create a .cshtml view and add a @model statement at the top of the page to bind to an instance of this MusicalTastes class. Use the @Html.CheckBoxFor() helper to bind to each property instead of the @Html.CheckBox() helper as you did in the last blog entry.

    @model BootstrapCheckBoxes2.MusicalTastes

     

    @using (Html.BeginForm())

    {

      <div class="form-group">

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

          <label class="btn btn-primary">

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

            @Html.CheckBoxFor(m => m.IsJazz) Jazz

          </label>

          <label class="btn btn-primary">

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

            @Html.CheckBoxFor(m => m.IsCountry) Country

          </label>

          <label class="btn btn-primary">

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

            @Html.CheckBoxFor(m => m.IsRock) Rock

          </label>

        </div>

      </div>

      <div class="form-group">

        <button type="submit"

                class="btn btn-success">Submit

        </button>

      </div>

    }

    Notice that the expressions you pass to the first parameter of this CheckBoxFor helper have the names of each of the properties in the MusicalTastes class. This is what binds this check box to each of the properties.

    Binding to Musical Tastes

    In the controller for this .cshtml page create an instance of the MusicalTastes class and set one or more of the properties to true in order to see the check box checked when the page displays.

    public ActionResult BindingTest()

    {

      MusicalTastes entity = new MusicalTastes();

     

      entity.IsCountry = true;

     

      return View(entity);

    }

    jQuery for Musical Tastes

    In order to get the correct display for any property set to true you need to write some JavaScript/jQuery to toggle the glyphs. Below is the code you would add to the end of the $(document).ready(). Keep the same code you had in the previous blog post to toggle the check boxes when you click on each one, but add code that will run when the page loads as shown in the bold code below:

    @section scripts

    {

      <script>

        $(document).ready(function () {

          // Connect to 'change' event in order to toggle glyphs

          $("[type='checkbox']").change(function () {

            if ($(this).prop('checked')) {

              $(this).prev().addClass('glyphicon-ok-circle');

              $(this).prev().removeClass('glyphicon-unchecked');

            }

            else {

              $(this).prev().removeClass('glyphicon-ok-circle');

              $(this).prev().addClass('glyphicon-unchecked');

            }

          });

         

          // Detect checkboxes that are checked and toggle glyphs

          var checked = $("input:checked");

          checked.prev().removeClass('glyphicon-unchecked');

          checked.prev().addClass('glyphicon-ok-circle');

        });

      </script>

    }

    This code selects all check boxes checked via the automatic data binding. It then removes the unchecked glyph and adds the ok-circle glyph to all those check boxes.

    Posting Back Musical Tastes Selected

    There is nothing to do to get the selected check boxes to post back to your entity class. Simply create a method in your controller with the [HttpPost] attribute. Pass in the entity class to this method and MVC will take care of matching the names of the check boxes to the appropriate properties in your entity class.

    [HttpPost]

    public ActionResult BindingTest(MusicalTastes entity)

    {

      System.Diagnostics.Debugger.Break();

     

      return View(entity);

    }

    I added the Debugger.Break() statement so I can hover over the ‘entity’ variable and verify that the check boxes checked have been updated in the instance of the MusicalTastes class passed in.

    Summary

    Binding an entity class with boolean properties to a set of check boxes on a .cshtml is very easy to do. Simply create your class and use the @Html.CheckBoxFor() helper class to bind your check boxes to the appropriate properties. Add a little bit of client-side JavaScript/jQuery to toggle the glyphs and you have a very nice looking interface for your check box controls.

    Read more...

  • Creating Checkboxes using Bootstrap and MVC

    The normal HTML check box just does not look good. Yes, bootstrap has a CSS class that will attempt to at least let it render consistently across browsers, but it still is just the default HTML look. In addition, trying to hit a check box on a mobile phone can sometimes be a little challenging.

    In an MVC project we are doing for a client, they wanted the check boxes to look more like buttons. Since we were already using bootstrap for this project we were able to create our own check boxes using the “btn-group” class from bootstrap. Let’s walk through how we created these.

    Normal Check Boxes

    As most of you know, creating normal check boxes in MVC is easy to do with the CheckBox HTML helper class. The code below is what you write for creating standard HTML check boxes in MVC:

    @using (Html.BeginForm())

    {

      <div>

        @Html.CheckBox("IsJazz") Jazz

        @Html.CheckBox("IsCountry") Country

        @Html.CheckBox("IsRock") Rock

      </div>

    }

    Bootstrap Check Boxes

    With bootstrap you add a <div> with a class of either “checkbox” or “checkbox-inline” around your check boxes. You also add a <label> element around the check boxes in order to use bootstrap’s styling of labels. Normally this gives you a bolder font for the actual text of the check box.

    @using (Html.BeginForm())

    {

      <div class="form-group">

        <div class="checkbox-inline">

          <label>

            @Html.CheckBox("IsJazz") Jazz

          </label>

        </div>

        <div class="checkbox-inline">

          <label>

            @Html.CheckBox("IsCountry") Country

          </label>

        </div>

        <div class="checkbox-inline">

          <label>

            @Html.CheckBox("IsRock") Rock

          </label>

        </div>

      </div>

    }

    Both of the above pieces of code will produce some output that looks like the check boxes shown in Figure 1.

    Figure 1: Normal HTML Check boxes

    Use Button Groups

    One of the classes that bootstrap supplies is “btn-group”. This class combined with the data-toggle=”buttons” gives you the ability to create check boxes that look like standard buttons but will toggle when pressed. What is nice about check boxes expressed this way is you can really tell that the label is a part of the check box. When you click on one of the buttons you will see it change color. In addition, these buttons are much easier to press on a mobile device.

    @using (Html.BeginForm())

    {

      <div class="form-group">

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

          <label class="btn btn-primary">

            @Html.CheckBox("IsJazz") Jazz

          </label>

          <label class="btn btn-primary active">

            @Html.CheckBox("IsCountry") Country

          </label>

          <label class="btn btn-primary">

            @Html.CheckBox("IsRock") Rock

          </label>

        </div>

      </div>

    }

    Note the use of the “active” class on the Country check box. This is what makes this one selected when you display the screen (see Figure 2).

    Figure 2: Check boxes displayed as button groups.

    Add Glyphs

    Users are used to seeing a check mark or an empty box next to the label for check box controls. So, you should add those into your design. Use the built-in glyphs in bootstrap to display a check or an empty box. Below is the code to do this:

    @using (Html.BeginForm())

    {

      <div class="form-group">

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

          <label class="btn btn-primary">

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

            @Html.CheckBox("IsJazz", true) Jazz

          </label>

          <label class="btn btn-primary active">

            <span class="glyphicon glyphicon-ok-circle"></span>

            @Html.CheckBox("IsCountry") Country

          </label>

          <label class="btn btn-primary">

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

            @Html.CheckBox("IsRock", true) Rock

          </label>

        </div>

      </div>

    }

    Take a look at the Country check box. There are two modifications to this check box. First, you add the “active” class on the <label> element. This makes it a different color from the other two check boxes. You also change the glyph in the <span> element from “glyphicon-unchecked” to “glyphicon-ok-circle” to give it a check mark within a circle.

    Feel free to use whatever icons you want. Font Awesome (www.fontawesome.io) has a lot of different CSS glyphs that you can use instead of the limited ones in bootstrap.

    Figure 3: Add glyphs to make the buttons look more like check boxes.

    Change Glyphs Dynamically using jQuery

    When the user clicks on a check box you want to toggle the glyph. Luckily when you click on the check box, bootstrap takes care of toggling the “active” class on the <label> elements for you. All you need to do is to write some jQuery to toggle the glyphs. Below is the jQuery code you add at the bottom of the .cshtml MVC page to toggle the glyphs.

     

    @section scripts

    {

      <script>

        $(document).ready(function () {

          // Connect to 'change' event in order to toggle glyphs

          $("[type='checkbox']").change(function () {

            if ($(this).prop('checked')) {

              $(this).prev().addClass('glyphicon-ok-circle');

              $(this).prev().removeClass('glyphicon-unchecked');

            }

            else {

              $(this).prev().removeClass('glyphicon-ok-circle');

              $(this).prev().addClass('glyphicon-unchecked');

            }

          });

        });

      </script>

    }

    This jQuery is fairly simple to understand. When the user changes the check box you determine if the check box is checked or unchecked. Based on this setting you either add or remove the appropriate classes from the <span> element that is just prior to the check box control.

    Summary

    In this blog post you learned how to present check boxes just a little differently. While it is not necessary to do this, I like the way these check boxes look and feel. With just a little use of built-in bootstrap CSS and jQuery you can get something that looks a little different from the traditional web look.

    Read more...

  • Using Friendly URLs in Web Forms

    Friendly URls help you eliminate query string parameters and file extensions from the URL line. So, instead of…

    www.url.com/Products.aspx

    www.url.com/Products.aspx?ProductId=3

    You use simple friendly URLs instead as shown below:

    www.url.com/Products

    www.url.com/Products/3

    There are many benefits of using friendly URLs in your web applications.

    ·         Cleaner query string

    ·         User does not know the actual page name

    ·         Easier for users to use

    Friendly URLs are available in Web Forms and MVC. I see a lot of examples of using friendly URLs using MVC, but very few using Web Forms. So, I thought I would discuss how to use them in Web Forms. Actually, the process is almost identical.

    First you need to download the Microsoft.Asp.Net.FriendlyUrls.Core.dll if you don’t already have it in your project. If you have an older ASP.NET application you probably don’t have it. If you are starting a new project in Visual Studio 2013, and choose the Web Forms template, this DLL is already present.

    If you want to use friendly URLs in an older project, select Tools | Nuget Package Manager | Manage NuGet Packages for Solution... from the Visual Studio menu. Search online for Microsoft.AspNet.FriendlyUrls and install the Microsoft.AspNet.FriendlyUrls.Core. You don’t need any of the other DLLs in the NuGet packages list, just the “Core” DLL.

    If you have an App_Start folder, check and see if you have a class called RouteConfig.cs in there. If so, then you already have what you need. If you don’t, then add a class called RouteConfig to your project.

    Add the following using statements at the top of this new class file.

    using System.Web.Routing;

    using Microsoft.AspNet.FriendlyUrls;

    Either add the following method, or modify it to look like the following. This assumes you have 3 pages in your project; Default.aspx, Customers.aspx, and Products.aspx. Feel free to substitute your page names as appropriate.

    public static void RegisterRoutes(RouteCollection routes)

    {

      routes.EnableFriendlyUrls();

     

      routes.MapPageRoute("", "Default", "~/Default.aspx");

     

      routes.MapPageRoute("", "Customers", "~/Customers.aspx");

      routes.MapPageRoute("GetCustomer",

                          "GetCustomer/{CustomerId}",

                          "~/Customers.aspx");

     

      routes.MapPageRoute("", "Products", "~/Products.aspx");

      routes.MapPageRoute("GetProduct", "GetProduct/{ProductId}",

                           "~/Products.aspx");

    }

    In the above page routes you have some parameter placeholders denoted by the curly braces {}. These are what you use to pass any parameters to and the names you use to retrieve those values.

    The next step is to open your Global.asax and either add, or check to see, if you have the following using statement at the top of the file.

    using System.Web.Routing;

    In the Application_Start() event you now need to call the RegisterRoutes method you created in the last step. The RouteTable.Routes object, created by the ASP.NET engine, is what you add to in your RegisterRoutes method.

    RouteConfig.RegisterRoutes(RouteTable.Routes);

    You can now run your ASP.NET application type in any of the following:

    http://localhost:xxxx/Products

    http://localhost:xxxx/GetProduct/22

    http://localhost:xxxx/Customers

    http://localhost:xxxx/GetCustomer/ABC

    From any <a> tag on your web pages you can now use the following syntax:

    <a href="Products">Get All Products</a>

    <a href="GetProduct/22">Get Product #22</a>

    Notice that you don’t need the “.aspx” extension. If you are using the Response object to redirect from code behind, may also use the same shorthand for any route that does not have a parameter.

    Response.Redirect("Products");

    Response.Redirect("Customers");

    Passing Parameters using the Response Object

    If you are going to pass either a customer id or a product id to your pages, and you want to use the Response object, you need to setup things a little differently. Remember you created the following map page route in the RouteConfig class.

    routes.MapPageRoute("GetProduct", "GetProduct/{ProductId}",

                        "~/Samples/ProductView.aspx");

    To redirect to this page, you use the RedirectToRoute method of the Response object.

    Response.RedirectToRoute("GetProduct",

     new {ProductId = 33});

    The first parameter you pass to the RedirectToRoute method must match the first parameter in the MapPageRoute. The second parameter is an object with the name in the braces {ProductId} set to the value you wish to pass (in the above case 33).

    Retrieve the Passed Parameters

    To retrieve the value passed you use the Page.RouteData.Values property. Pass in the name of the parameter you are looking for, in this case “ProductId” and it will return either a null if not found, or the value. You typically retrieve these values from the Page_Load event procedure.

    if (Page.RouteData.Values["ProductId"] != null)

    {

      int ProductId =

         Convert.ToInt32(Page.RouteData.Values["ProductId"]);

    }

    Summary

    Using friendly URLs is quite easy to accomplish in either Web Forms or MVC. You can download the friendly URLs “Core” DLL from NuGet to add to any project. Then with just a few lines of code you can start calling your pages in a very user-friendly manner.

    Read more...

  • Web Forms is not Dead!

    It seems like everywhere you read, everyone is talking about using ASP.NET MVC to create mobile web applications. But what about programmers still working in ASP.NET Web Forms? We want our projects done using the latest techniques, we want to build mobile web apps, and we want to use jQuery and bootstrap too. Not to fear, Web Forms is not dead, and nearly everything you can do in MVC, you can also do in Web Forms. I am creating a whole series of videos on how to use all the latest techniques in Web Forms to build modern web applications. This series of videos will be available in the summer of 2014 on www.pluralsight.com.

    MVC vs Web Forms

    Many programmers feel they have to choose one technology over another. But, there is really no reason you can’t program in both MVC and Web Forms and use each for what they are good at.. Many MVC programmers give many reasons why you should use MVC as opposed to Web Forms. The reasons I hear more often are:

    1.    Fine control over the HTML generated

    2.    Ability to unit test

    3.    Can control the “id” attribute generated

    4.    Easier to use jQuery and JavaScript because no generated “id” attribute

    5.    Ability to use Friendly URLs

    6.    No ViewState sent to client

    Of course, programmers that like Web Forms have many reasons why they want to stick with it:

    1.    Rapid Application Development

    2.    Less code to write because of rich server controls

    3.    Lots of server controls to choose from

    4.    Great third-party support

    5.    Easy to preserve state

    6.    They like the event driven model

    7.    Hides the complexity of the web

    8.    More mature so there is more information with respect to questions, problems, etc.

    In this article let’s explore how Web Forms will let you get very close the MVC model. There are many things you can take advantage to get Web Forms to work almost exactly the same as MVC, and you do it using the tools you already know and love.

    HTML 5 and CSS 3

    In any Web Form page you can use HTML 5 elements and attributes. Even if you are using a server control you can still add any attribute to the control and it will emit the attribute for you. CSS 3 is just a new version of CSS and we have always been able to use CSS with Web Forms, so there is no difference here. The TextBox control now supports the HTML 5 input types such as date, tel and email through the TextMode property.

    ViewState

    Most Web Form pages do not need ViewState to work property. There are just a few cases when you will need to turn on ViewState. I recommend disabling ViewState in the Web.Config and then just turn it on when you get to a page that just does seem to work right. By turning this off you will see an increase in performance because not as much HTML is sent down to the client.

    Store ViewState on the Server

    If you still need to use ViewState, but you do  not want the extra hidden field to be sent to the client, you can easily store ViewState on the server. This functionality has been available since .NET 1.0. You simply override two events in the base page class; LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium. These two events will allow you to store and restore the view state on the server and not send the hidden field to the client.

    Friendly URLs

    Using “RESTful” or so-called SEO-friendly URLs is all the rage today. What is nice about these URLs is it makes for a cleaner query string, the user does not know the actual page name and is typically easier for users to access and remember.

    Instead of these…

    www.url.com/Products.aspx

    www.url.com/Products.aspx?ProductId=3

    Use Friendly URLs instead…

    www.url.com/Products

    www.url.com/Products/3

    To add friendly URLs to your project simply go to Tools | Nuget Package Manager | Manage NuGet Packages for Solution... Search online for “Microsoft.AspNet.FriendlyUrls” and install the “Microsoft.AspNet.FriendlyUrls.Core”.

    Add a class called RouteConfig and add the following using statements at the top of the file:

    using System.Web.Routing;

    using Microsoft.AspNet.FriendlyUrls;

    Now add a method named RegisterRoutes.

    public static void RegisterRoutes(RouteCollection routes)

    {

       routes.EnableFriendlyUrls();

     

       routes.MapPageRoute("", "Default", "~/Default.aspx");

    }

    You can add as many MapPageRoutes as you want in this method. You just have to keep the first and second parameters unique.

    Now in your Global.asax you will add a using statement at the top of this file:

    using System.Web.Routing;

    In the Application_Start() event you will call the static method you created in the RouteConfig class.

    RouteConfig.RegisterRoutes(RouteTable.Routes);

    MVVM

    I have written a blog post and an article on using the Model-View-View-Model approach to software development. If you use MVC or Web Forms you should be using a View Model. The View Model is where all of your data access happens and all the code to control the UI should also be located. The controller in MVC calls the View Model and the code-behind in Web Forms calls the View Model. This means that all unit testing happens on the View Model and you do not need to test against a controller or the code-behind file. You can read more about this model at the following two links.

    http://weblogs.asp.net/psheriff/the-basics-of-mvvm

    http://www.codemag.com/article/1208031

    Unit Testing

    As just mentioned above, if you use the MVVM design pattern you get the benefits of being able to do unit testing and take advantage of TDD if you so desire. 

    jQuery and JavaScript

    Using jQuery and JavaScript is an absolute must when building today’s modern web applications. Web Forms used to be criticized because when it generated the HTML controls, it “munged” the id attribute. This means that the id that you used in your ASPX page was something different when it ended up on the client. This makes it hard to know what the name is when you want to reference that control in jQuery or JavaScript.

    Microsoft gave us the ClientID property and the UniqueID properties to access the id and name attributes respectively. However starting with .NET 4.0 they added a ClientIDMode to the page level and to the Web.Config file. This allows you to set the ClientIDMode=”Static” and the id you set in your ASPX page is what will be generated on the client. This makes integrating with jQuery and JavaScript just as easy as it is with MVC.

    Bootstrap

    Twitter Bootstrap is a very powerful and popular CSS and JavaScript library that allows you to create responsive web sites. We have been using bootstrap for a few years now and it works just fine in Web Forms. We have successfully implemented templates we purchased from wrapbootstrap.com and themeforest.net. We typically take these templates and integrate the navigation and other elements into our Web Forms master pages. We then build very nice looking responsive web applications using Web Forms.

    GridView

    Web pages love tables! However tables are not always a good thing on smaller devices like a smart phone. Using bootstrap styles in combination we can make the GridView work much better. A better approach is to use the GridView so you get the built-in paging and all the great features of the GridView but make it not look so tabular. I wrote a blog about how to create an alternate view of tabular data. Check out this approach on how to present data that will work better on a mobile device:

    http://weblogs.asp.net/psheriff/an-alternate-approach-to-a-gridview

    Additional Guidance

    One thing I like to do is consider what other folks are saying about Web Forms vs MVC. If you look at the following names, you can see what some of the heavyweights in the industry have to say.

    Scott Guthrie

    “Web Forms and MVC are two approaches for building ASP.NET apps. They are both good choices.”

    http://weblogs.asp.net/scottgu/archive/2010/01/24/about-technical-debates-both-in-general-and-regarding-asp-net-web-forms-and-asp-net-mvc-in-particular.aspx

    Dino Esposito

    “ASP.NET MVC doesn't magically transform every developer into an expert architect and doesn't prevent developers from writing bloated and poorly designed code. At the end of the day, both Web Forms and ASP.NET MVC help to build applications that are designed and implemented to deal effectively with the complexity of real-world solutions”

    http://msdn.microsoft.com/en-us/magazine/dd942833.aspx

    Jeffrey Palermo

    “It is rarely a good idea to trash your current application and start over”

    http://clear-measure.com/i-have-a-web-forms-custom-application-should-i-upgrade-to-asp-net-mvc-now-or-wait/

    K. Scott Allen

    “…figure out for yourself what framework will be the best for you, your team, and your business.”

    http://www.odetocode.com/blogs/scott/archive/2013/02/12/you-want-to-build-web-software-with-c.aspx

    Microsoft

    A good overview of which to use when.

    http://www.asp.net/mvc/tutorials/older-versions/overview/asp-net-mvc-overview

    Public Sites Favors MVC

    What we have gathered from our own experience and from reading what others are using MVC for are the following types of sites.

    ·         Blogs

    ·         Web content

    ·         Marketing

    ·         Membership

    ·         Shopping

    ·         Mobile

    Business Apps Favor Web Forms

    We have found that for building business applications that are doing a lot of CRUD operations that Web Forms lends itself really well to these types of applications.

    ·         Line-of-business

    ·         SaaS

    ·         Extranet

     

     

    Summary

    In the end it is up to you which approach you are going to use when developing your web applications. But you should not let folks that are clearly biased toward MVC sway your choice. Web Forms is still a great choice for developing web applications. Just because Microsoft releases a new technology does not mean that you should immediately trash everything you know and jump on it.

    As you have seen in this article, Web Forms and MVC are based on the same underlying technology and both can generate fast, small, responsive web applications. At the same time both can be unit tested, take advantage of MVVM, HTML 5, CSS 3 and jQuery libraries. So don’t throw away all your hard-earned skills, just take advantage of the tricks in this article and develop modern web applications with Web Forms.

    Read more...

  • Join me on Thursday, April 10th in Nashville

    Hi All,

    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".

    Seminar Description

    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!

    Paul Sheriff

     

     

    Read more...

  • WPF for the Visual Basic Programmer - Part 2 (Pluralsight)

    Hi All,

    I have just published a new course on www.pluralsight.com. Check it out! 

    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 2 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.

    http://pluralsight.com/training/Courses/TableOfContents/wpf-vb-programmer-pt2

    Enjoy!

    Paul

     

    Read more...