22 Apr

Angular 2 contact form component for ASP.net MVC 6

Angular2
In my last post I showed you how to work with Angular 2 and the Bootstrap Carousel.
In this post I want to show you how to create a simple contact form using Angular 2 and ASP.net MVC 6, the most recent releases of both technologies.

The component

contact.cshtml

We’ll start off with a simple contact form. I’m asking the user for his name, e-mail address, a subject and of course the message itself.
You’ll notice that I’m also using a bit of Bootstrap CSS classes. You however can of course use anything you want to style the contact form.

<div>
    <form #f="ngForm" (ngSubmit)="onSubmit(contact)">
        <div>
            <div class="form-group required">
                <label for="name">Name</label>
                <input type="text" [(ngModel)]="contact.Name" name="contact.Name" required="Please enter your name" class="form-control text-input" id="name" placeholder="Name"/>
            </div>
            <div class="form-group required">
                <label for="email">E-mail</label>
                <input type="email" [(ngModel)]="contact.Email" name="contact.Email" required="Please enter your e-mail address" class="form-control text-input" id="email" placeholder="E-mail"/>
            </div>
        </div>
        <div>
            <div class="form-group required">
                <label for="subject">Subject</label>
                <input type="text" [(ngModel)]="contact.Subject" name="contact.Subject" required="A subject is needed" class="form-control text-input" id="subject" placeholder="Subject"/>
            </div>
        </div>
        <div>
            <div class="form-group required">
                <label for="message">Message</label>
                <textarea type="text" [(ngModel)]="contact.Message" name="contact.Message" required="A message is needed" class="form-control" id="message" placeholder="Message..."></textarea>
            </div>
        </div>
        <div>
            <div>
                <button type="submit" class="btn btn-success">Send</button>
            </div>
        </div>
    </form>
</div>


contact.ts

This the most important part of this post. I’ve written the code in Typescript.
Due to an issue I couldn’t seem to resolve between MVC6 and Angular 2 I was forced to the URLSearchParams from Angular to send my data to the server. I hope to update this one day so I only have to send the complete object to the server.

import {Component} from '@angular/core';
import {Http, Headers, URLSearchParams} from '@angular/http';

@Component({
    selector: 'contact',
    templateUrl: '/angular/contact'
})

export class ContactFormComponent {
    http = undefined;
    contact = { Name: undefined, Subject: undefined, Email: undefined, Message: undefined };
    loading = true;

    constructor(http: Http) {
        this.http = http;
        this.loading = false;
    }

    onSubmit() {
        this.loading = true;
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        this.http.post('/contact/send', JSON.stringify(this.contact), options).subscribe(() => {
            this.messageSend();
        });
    }

    private messageSend() {
        this.contact = { Name: undefined, Subject: undefined, Email: undefined, Message: undefined };
        this.loading = false;
    }
}

This was the biggest part, now what’s left is the connection on the server itself.

Start.cs

First we’ll setup the routes. This is very easy. I’ve set up a route to go to the contact form itself and one for sending the information to the server.

public class Startup
{
	public void ConfigureServices(IServiceCollection services)
	{
		//I'm using MVC... So I'm adding MVC.
		services.AddMvc();
	}

	public void Configure(IApplicationBuilder app)
	{
		//I have some static files, like images and CSS in my wwwroot folder. So I need to add these.
		app.UseStaticFiles();
		app.UseMvc(m =>
		{
			//Route to open the page with the form.
			m.MapRoute("contact", "contact", new { controller = "Contact", action = "Contact" });
			//Route to post the data
			m.MapRoute("contact-send", "contact/send", new { controller = "Contact", action = "SendContact" });
		});
	}

	// Entry point for the application.
	public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}


ContactVm.cs

This is going to be the ViewModel. I use this to map the JSON request to a nice and easy model we can use on our controller.

public class ContactVm
{
	[Required]
	[DataType(DataType.Text)]
	public string Name { get; set; }
	[Required]
	[DataType(DataType.EmailAddress)]
	public string Email { get; set; }
	[Required]
	[DataType(DataType.Text)]
	public string Subject { get; set; }
	[Required]
	[DataType(DataType.MultilineText)]
	public string Message { get; set; }
}

ContactController.cs

The last part is our controller itself where the data is being received on the server.
Nothing special here, I’m just using the above ViewModel as a parameter.

public class ContactController : Controller
{
	public ContactController() { }

	public IActionResult Contact()
	{
		return PartialView();
	}
	
	[HttpPost]
	public void SendContact(ContactVm contact)
	{
		//Do something with the contact form...
	}
}

By using the above code you’ll be able create a contact form in Angular 2 and make it interact with and MVC 6 server-side.
Keep in mind the both frameworks are still in development and can contain errors.



Let me know your feedback or questions in the comments below and I’ll be happy to answer them!

3 thoughts on “Angular 2 contact form component for ASP.net MVC 6

    • Hi Tanzeel!

      I know it’s not the common way of using angular, but like this example I tend to use .NET MVC views instead of just .html. More info on the template I’m using you can find at https://thecodegarden.net/dotnet-core-angular-template/.

      You can use the .cshtml file just like any other .html file. You need to return it as a partialview though, otherwise you’ll end up having multiple -tags and stuff.
      But the route in the templateurl is just pointing to controller which is returning the view.

      But, you can easily change the .cshtml to a simple .html if that’s more your thing.

      • Hey Jeffrey thanks for the immediate reply ,yes I am also dealing with .cshtml so as to use @Viewbag for server side data.I didn’t realize that templateUrl was pointing to the controller mentioned in Startup.cs file.Thanks a lot for the great article , there are not many articles which handles the case of MVC Views with angularjs

Leave a Reply

Your email address will not be published. Required fields are marked *