WPF Label – Click and Focus on Element

WPF applications have labels and controls but, unfortunately, they don’t integrate together as easily as in HTML. In HTML you rely on the id and for attributes to bind them together. Then when the label is clicked the control gets focus. So in that environment labels serve to identify the control, as well as aid in accessing it. Sometimes it’s easier to click on a label then the form element itself, such as with checkboxes and radios.

I wanted to achieve the same effect in WPF. I accomplished this by creating and referencing my own customized label. The new label inherits all the features of a traditional label but also includes a few others.

To begin, we create the class. Out of the box a WPF label will stretch horizontally to fill the entire area it resides in. By setting the HorizontalAlignment it collapses it down to the width of its content. This can be overridden in the xaml. We then give the element focus based on a mousedown event.

I also have a bit of code just for textboxes. Once focused the cursor will be placed at the front of any text. You can use the code below to move the cursor to the end, or select the text.
Next, we need to reference the new label in the xaml. To do this we must declare a namespace in the Window object then reference it on each call to the control. The example shows EnvelopePrinting. Replace that with the name of your namespace. We also use Target attribute and Binding call to link the two elements together.

Read More

Self-Closing Bootstrap Alert

Alerts are a nice feature in Bootstrap to grab a user’s attention and deliver information. The different types of alerts are success, info, warning and danger, which are color coded accordingly. Alerts can include a close button for users to remove it from view once they have read it. In my project I wanted success alerts to show to users then, after a few seconds close on their own. This can be done easily with jQuery’s fadeTo() function. You can also incorporate a slick transition effect with the slideUp() function.

Create a success alert via bootstrap
Then you just need a little script. This script targets only success alerts and will close it after 5 seconds:
See a DEMO.

Read More

Using ASPX Like MVC

I love the organization of MVC when it comes to delivering content. Using a server-side controller you can see all the routing activity of your program. The controller can interact with the parent view as well as related partials, passing data and rendering html. Related views are also tucked-away together in the tree making it easy to pinpoint what you’re looking for. The default layout of WebForms is a different kind of animal. But using MVC experience as a reference you can structure your project to work in a similar way.

To begin we want to create a Views folder and inside that create a Home directory. The Home directory will contain the parent ASPX as well as any child ASPX pages for the dynamic content. When naming the child ASPX files be sure to prefix them with an underscore to follow MVC convention:

Tree Example

Next, we need to refine the Site.Master (or _Layout.cshtml in MVC). Make sure to add the script and style bundles to get jQuery and Twitter Bootstrap on the page. The ContentPlaceHolders (or sections in MVC) allow us to have placement control:
If any bundles are missing they can be added in App_Start/BundleConfig.cs.

In this example the parent ASPX contains a button that performs an ajax request. ContentPlaceHolders are used to inject code snippets in the proper location within Site.Master:
This is pretty straightforward. The script performs an ajax request to a partial ASPX. It passes data and retrieves HTML that is displayed to the user. The Index.cs file is not touched.

Next, we want to ensure the server can locate our parent page. A simple adjustment to the Web.config can accomplish that:
Now on to Models. You can also create Models to share between parents and partials. When creating a new Web Forms templated project it comes with a Models folder already. Inside is a model for account identity. Create a HomeModel.cs and place it in that folder. Next, add the following model to it which will be referenced later:
In any ASPX file you can add a using statement to reference our models:
Replace WebForms_Ajax with the name of your project. After that, all models can be shared between ASPX pages. This can reduce redundant coding.

The last step of the process is the partial. Under /Views/Home create an ASPX page named _Incomplete.aspx. The UI looks like:
Notice we have a full HTML document here. This is necessary to use the ASP.NET Web Server Controls. If you don’t include surrounding <html> tags then it won’t recognize tags prefixed with asp. But don’t worry, when we return the markup via ajax it won’t have any of that. We simply grab the contents of the <asp:PlaceHolder> tag.

Take note of the tags. This is what we use to add data to our page. They will repeat one to many times to add content to the page. Inside that repeater is another repeater whose data source is set automatically. The Eval() calls relate to the property names of our model.

The code behind does the magic. In Page_Load we fetch the data that was passed. It can be used to retrieve any additional information from a data source. Next, we construct our model to pass to the page. The model was declared in HomeModel.cs The RootRepeater is the name of the outermost repeater. We set the class equal to it’s data source. Notice we are placing the model in a list. A repeater requires a list or other IEnumerable object to work. Lastly, we grab the contents of the placeholder and return it with the response:
Download a DEMO.

Read More

Ajax to Retrieve HTML Segments from Single ASPX

Have you ever wanted to have one ASPX file that can render normal content as well as dynamic content? The dynamic content can return HTML that utilizes ASPX server controls. The segment returned is not cloned from hidden markup preexisting on the page, but rather is foreign and new as far as the DOM is concerned. If so then follow these steps to create one relay station for all your content:

In the aspx file we define a section that is reserved for our ajax request:
Of course this page also has other HTML and script that will render/bind on page load:
The script wires up the button. Here, we are using jQuery’s $.load function:
Alternatively, you can use $.ajaxto make the request. Note that I do not have a contentType or performing json encoding:
So onto the code behind. These alternations handle the initial load request as well as any subsequent ajax requests:
If you walk through it you can see we are routing everything through the HandleCallbacks method. We check for an ajax request. If one is not declared then we exit gracefully and everything is rendered in the ASPX apart from our placeholders. If it is an ajax request we retrieve our data, assign it to the repeater, make it’s placeholder visible, then render the segment using a writer. The transformed markup is returned as part of the Response and we load it into a location of our choosing.

Download a DEMO.

Next, we will cover how to make ajax requests to separate aspx files.

Thanks.

Read More

Self-Closing Bootstrap Modal in MVC

I had a need recently to alert users if the amount of records being selected differed from what they expected. My notice was more of a "heads up" then anything. Still, I wanted to give users a way to abort situations where job size would pose a threat or hinder productivity. I also wanted to avoid extra interface clicks, especially in situations where they typically accept. That’s when I came up with the idea of a self-closing dialog. The user would be presented a modal message informing them of the difference. To proceed they could press the Continue Immediately button, close the dialog (via the title bar), or step away and wait for the timer to run out. The process only aborts if they they click the Cancel button in the allotted time.

This project could be done in a multitude of ways. Being an MVC fan I opted for that route. I decided to utilize partial views as well. Regardless of your approach you will likely need to contact the server to crunch your numbers and detect the differences. To do this you will probably use ajax:
On the backend we receive our data using a controller and models:
Next, comes the partial view. Notice I’m declaring a model and using it to retrieve values:
I also have some script in the partial to drive the modal:
And there you go.
  1. We click a button that fires ajax
  2. The ajax talks to the server
  3. The server detects differences
  4. The server populates a model then generates a partial view
  5. The partial view is returned to the ajax callback function
  6. The callback function adds it to the DOM and executes the script

Like I said this could be done in a dozen different ways. You could have the modal hidden on the parent, use ajax to fetch the figures themselves, then modify the modal before making it visible (see DEMO below). You could also use webforms to do this and use ASP.NET web server controllers instead of partial views.

See a DEMO.

Thanks.

Read More

DataTable Fundamentals Part 1

I’m a big fan of jQuery DataTables. It’s my new grid of choice for interfacing. I jumped on the bandwagon at at the release of 1.10.0 which was a major versioning change/re-working. The documentation was lacking a bit at the time so I had to do a lot of trial and error to figure things out. I used jqGrid for years before making the transition. I find DataTables to be cleaner (as far as object organization) and more understandable. I feel that any programmer that comes behind me will have an easier time deciphering code I’ve written for DataTables verses jqGrid. It also looks more like a table to me as opposed to some kind of widget. You can probably accomplish more advanced things with jqGrid, but a lot of that is unnecessary fluff that doesn’t lend itself to the real, business world.

Display Values

Some trivial features alluded me at first. Such as how do I modify the display without compromising the underlying data? Some record values don’t translate well for users. For instance, in a database record you may have a field with a value of stdenv, but you want to show it as Standard Envelope to the user. If your code continues to interact with the database you may need to retain that original value.

In jqGrid you would often use a formatter. To translate a date you may do something like this:
So how do you do this in DataTables? When working with this plugin I’m almost always using an ajax data source as objects. I thought I was translating this correctly by manipulating the ajax result via the ajax property but later found out that was changing the underlying data. Then I discovered I could change it in the createdRow property. That technique was okay but for every cell that renders there is two DOM writes (the write by the plugin, then my translated overwrite). Finally, I came across an elegant solution that makes me happy. I already have a columns property defined in my DataTable object:
To translate a value I use the render property. You can read about it here. It can be as simple as this:
You can also translate the data in these types of ways:
To set a default value use the defaultContent property. You can read about it here:

Sub-Sorting

Sometimes you want your grid to sub-sort related columns when sorting on a column. This is simple to declare as well using the orderData property. You can read about it here:
The column indexes are in the order they appear: name: 0, position: 1, date: 2. So clicking on position will sub-sort name. Likewise, sorting descending on position will sub-sort descending on name.

Read More