Friday, September 25, 2015

Creating a very simple Ajax Form in ASP.NET MVC 4

In this post, I am going to demonstrate how to create a simple Ajax Form in ASP.NET MVC 4 application using Visual Studio. I am using Visual Studio 2015 but this should work with VS 2013 too. We are going to submit information about a person using some ajax and with minimum use of javascript. There is javascript used but we are taking advantage of the wonderful tooling and template benefits of ASP.NET MVC4. I assume you know some basics of ASP.NET MVC 4 but to get started you create a default asp.net mvc 4 application inside visual studio.

Before diving right into code you may want to check the pre-requisites section below.

PREREQUISITES

Packages.

You will need if not already installed jQuery, jQuery.UI.Combined, jQuery.Validation, Microsoft.jQuery.Unobtrusive.Ajax, Microsoft.jQuery.Unobtrusive.Validation. Below is how my packages look like.

First we create a person class i.e model in the models folder inside your application. Notice the data annotations used to trigger form validation. These will be triggered on the client side when the user enters invalid information. Most of them are self explanatory however special mention to the confirm password field. It is so easy to do password confirmation here.

In the code above we specify that this form will take in strongly typed model Person. In the register-main div we have two things, one is loading image which is a spinning .gif image that you can easily get from internet and the other is a Partial view called _RegisterForm.cshtml that accepts our Model object. We will create _RegisterForm in the next step. In the Scripts section we use Jquery to configure our date picker to show month and year field to select Birthdate. Lets’ create _RegisterForm view using the create template with Person as strongly typed object. Now I have modified the form to use Ajax.BeginForm. See description of the code below.

In the above code, first line is obvious it takes in Person object. We wrap everything into ajaxForm div. The key parts here are as follows:

1. Using Ajax.BeginForm allows us submit form using Ajax. The parameters say that when I click on the submit button please post this form using “Register” action on the “Home” controller which accepts “POST” request. After the form is submitted replace the contents of “ajaxForm” div with result of request and while you process the request display the loading image we specified earlier.

2. Everything inside div form-horizontal is created using create a new asp.net mvc 4 view with a strongly typed model of type person. I modified the Birthdate field to take in the jquery ui date picker pay attention to the data_date attribute eg. data_date = "birthdate" we had inside the Register page.

Now we are going to see how everything clubs together. Until now you may be a bit lost. So lets check out our controller. In the home controller create following methods.

When you run the application and navigate to /Home/Register page it will hit the first Register method and display the Register.cshtml view. And inside Register.cshtml we have _RegisterFrom.cshtml partial view which will ultimately render the form. After filling the form out when you click on the submit button the second Register method is called that takes in a Person object. This register method returns a PartialView in both the cases 1. if the form is successful 2. if the form has errors. Lets’ understand the second Register method in a little bit more detail.

1. This method uses async and await since you may be submitting the form to a database or checking validation against a web service asynchronously. Special notice – See the async keyword on the method signature and because of that we cannot just return PartialViewResult we have decorate the method signature with Task<PartialViewResult>. For demo purposes, I am using await Task.Delay(1000) instead of an async web call.

2. The first if statement checks if the username is already taken or not. This is just for demo purpose but you may have some complex validation on the server side and if any field is invalid then you want to throw that error back and the user should see it below that field. See the image below. You do that by using the ModelState.AddModelError method which takes in field name and error message. In our case we wanted to display that this username is already taken so we have specified ModelState.AddModelError(“username”,String.Format(”username {0} is already taken”,person.username); Because of this statement our person model that was submitted by the user is invalidated and we return the same _RegisterForm.cshtml Partial view with person model.

3. If the model was valid then we enter into the second if statement and submit our person to a database or call a web service. Based upon you business logic you can do other things like if the form was unsuccessful show different message etc. In our case we are showing a partial view called _RegistrationResult.cshtml. You can modify this view to display either confirmation or error message.

Last but not the least to show stuff properly I am using following CSS.