.NET, web, community, architecture, practices

I’m working on a project where the Bootstrap modal dialog is being used to popup data entry and other forms. I had it working using jQuery to handle the Ajax call to the Controller. It was a lot of work to gather the form data into the JSON packet, call the Controller and handle the return values, especially if the form did not pass validation.

I thought there had to be better way. Here are the requirements I had:

The Bootstrap dialog must be modal

The form should not be loaded into the browser with the page. It will be read from the server when needed and then displayed.

The data must be sent via Ajax to the server.

If possible, validation should be performed client-side, before sending data to the server.

The form should stay open if Model Validation fails and validation messages should be displayed.

I did what any good developer does…I hit a search engine and found several articles that I had to piece together to make it all work. The process is quite simple:

An Ajax request is sent from the browser.

The server returns a partial view to the browser.

Javascript code receives the form and it is placed as HTML into a specified div.

The form is displayed.

When the user clicks Save, the form data is sent to the Controller, just as any form data but with one exception…it’s sent as Ajax.

The Controller method validates the data. If it passes validation, the data is saved, a success message is sent back to the server and displayed to the user, then the form is closed. If the data fails validation, it is returned to the form and the validation messages are displayed.

First, I had to setup the initial request. I put an empty div in the _Layout.cshtml file. This way, I can display dialogs from anywhere in the application.

Look at the Ajax.BeginForm statement OnSuccess, OnFailure, OnBegin, OnComplete define Javascript functions that run when the specified event occurs. I created dummy methods that do nothing and placed them in genericDialog.js. Then, I can override each one, simply by providing a different Javascript function, for example updateAddressSuccess.

And that’s all there is to it. A simple dialog that is loaded on-demand. You can also use the same methodology to load ANY partial view on demand. For example, you may have a complex form with multiple tabs and only load the tab data when the user clicks on it. Finally, you can use this method to make your forms seem faster. Because you won’t have to load up everything in the form, it gets generated faster and less data is sent to the browser on initial load, making the application seem faster. Your users will thank you.