In this post, I will show you simple tutorial about how to create a simple contact form using Angular 2 and ASP.NET MVC 6. Ok, let’s get started.
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/x-www-form-urlencoded' });
var params = new URLSearchParams();
params.set('Name', this.contact.Name);
params.set('Subject', this.contact.Subject);
params.set('Message', this.contact.Message);
params.set('Email', this.contact.Email);
this.http.post('/contact/send', params.toString(), { headers: headers }).subscribe(this.messageSend());
}
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 rout 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 View();
}
[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.