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.


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.


Read More

AJAX and Bootstrap Tabbing in MVC

In this tutorial you will see the Twitter Bootstrap tabstrip in action. I will be using MVC, Razor and jQuery to accomplish this. If you visit the tabstrip documentation you will see an example that uses static tab content. I have expanded upon that code snippet, converting it to dynamic content using AJAX. I’m also utilizing a fading transition effect as the content loads. The tabstrip will interact with two partial views named: _SearchTab.cshtml and _SubmissionTab.cshtml. Notice that I am naming the tab ids the same as the partial views. Doing that reduces translation in the script when relaying the AJAX calls.


The @Html.Partial will request the page on the active tab on page load. Place this call wherever the active class is being set.


The $.ajax() request retrieves the partial view. The cache parameter is necessary to ensure a fresh rebuild on each click. As for what path is requested you will notice a @ViewContext.RouteData.Values["controller"] call. It simply retrieves the controller of the current view, assuming the partial views are located in the same folder in the tree.


The above methods are needed to relay the $.ajax() request to the proper partial view.

Now each time you click on a tab it will load dynamic content from a partial view. Keeping content separate can keep code cleaner and more organized. Download an example implementing this technique.

Read More

Merge HTML Template with XML Data Source

I was recently working on a project where I needed to create an HTML receipt for a client. Instead of building the HTML on the fly I decided to keep the data and display separate. My goal was to create a mail-merge type of process where XML is referenced in an HTML template. I accomplished this using XSLT. This article explains the steps I performed to complete this process.

I began by adding the details of my receipt into XML using the XmlDocument object. To make this easier I added some helper extensions to my project. These extensions make it easy to add child nodes and attributes:
Next, I created the XML. Here is a sample with some random ids, names, and prices that would normally be fetched from a DataSource:
So what does this output look like? To see for yourself you can set a break-point after the code, and run it. Hover over the xml variable and look at the InnerXml. The above code generates the following XML structure:
Next, I created an XSLT file. I usually place this in the project's bin > Debug folder so it is easily referenced after publishing (nugets typically do this too). If you don't see that directory in your Solution Explorer click on the "Show All Files" icon in the top toolbar of that window. Right-click on the Debug folder > Add > New Item > Data > XSLT File. Give it a name like InvoiceTemplate.xslt then Add.

A new file will be created with some pre-generated code. We will replace the contents xsl:template with our own HTML page:
Let's dissect this a bit. A large portion of this is the HEAD section with some inline CSSS. In the BODY you will notice a reference to:
Since the first node is "order" then it is a reference to it's id attribute. Next, I built a table to show the items. Notice a loop around the TR tags with the following call:
The select attribute targets the items/item nodes using XPATH. For each ITEM in our XML it will generate a new row. Our first column is for row numbers and set using the position() function. It outputs the current loop iteration index starting with 1. For the second column we read the name attribute from ITEM much like we did the order id. In the third column we take it a step further by retrieving the price and also formatting it:
This will convert the price to US currency using a leading dollar sign, thousands separator, and a two digit remainder. After we exit the loop there is a "Total" row. That cell includes the sum() function:
It tallies the prices for all ITEM nodes and formats the resulting number to US currency.

Next, we need to merge the XML and XSLT. I used the following class to return me a string. It reads your XSLT file into an XmlReader and passes it to an XslCompiledTransform object. It then calls that object's Transform method passing in our XML. It returns the modified output as a string.
Finally, I called this class to retrieve the HTML. To see it in action I created the folder C:Testing. The following code will generate and open an HTML file on the fly with the string you provide:
Give it a try. If you don't see anything then it could be due to the parser not liking empty tags. I've had issues with leaving the tag blank, or including empty tags. When everything works you should get something like this:


That’s about it. Take your HTML and create a page or plug it into an SmtpClient request and send it as a richtext email. Download my sample project if desired.

Read More