Let’s create a contact page for our contacts. Instead of creating a new View Model, we will be using existing ContactVM, but we will do some amendments for the purpose of validation. We are going to extend our Application from the last discussion CRUD Operations In ASP.NET Core 1.0 MVC Application - Part Three.
Add CreateContact Method in ContactBusinessLogic
- Open existing solution in Visual Studio 2015.
- Open WebApplicationCore.NetCore.BusinessLogic.ContactBusinessLogic class.
- Add new CreateContact method.
- It may add new contact in mockup list data.
- public Contact CreateContact(Contact contact)
- {
- contact.ContactId = ContactBusinessLogic.Contacts.Count + 1;
- ContactBusinessLogic.Contacts.Add(contact);
- return contact;
- }
Add CreateContact Action Methods in ContactController
- Add two new CreateContact Methods.
- CreateContact method with the no parameter and HttpGet attribute to explicitly specify that this is a get method. It will be used to initialize and create a "Create Page". We will pass a view; an empty ContactVM.
- CreateContact method with the parameter of ContactVM type and HttpPost attribute to explicitly specify that this is the post method. It will be used to validate an input at Server side and to create an object.
- Post method may use ModelState.IsValid property to check, if the model does not have any error.
- Transform ContactVM object to contact object and pass it to ContactBusinessLogic().CreateContact for the further processing.
- If no error is found, we have performed all the activities successfully. We can move to another page, for example, in our case, we may navigate to the main list page. Alternatively, we may return the same view with the current object for the reprocessing.
- It is not required to have both methods with the same name, but it is conventional and has been in practice for a long time.
- RedirectToAction is used to redirect to some other view.
- [HttpGet]
- public IActionResult CreateContact()
- {
- ContactVM contactVM = new ContactVM();
- return View(contactVM);
- }
- [HttpPost]
- public IActionResult CreateContact(ContactVM contactVM)
- {
- if (this.ModelState.IsValid)
- {
- Contact contact = new Contact
- {
- Address1 = contactVM.Address1,
- Address2 = contactVM.Address2,
- City = contactVM.City,
- ContactId = contactVM.ContactId,
- ContactNumber = contactVM.ContactNumber,
- Country = contactVM.Country,
- Email = contactVM.Email,
- Name = contactVM.Name,
- ProvinceState = contactVM.ProvinceState,
- WebSite = contactVM.WebSite,
- ZipPostalCode = contactVM.ZipPostalCode
- };
- ContactBusinessLogic contactBL = new ContactBusinessLogic();
- contact = contactBL.CreateContact(contact);
- if(contact.ContactId>0)
- {
- return RedirectToAction("Index");
- }
- }
- return View(contactVM);
- }
Add Contact CreateContact View
- Add new View to Contact\Contact folder.
- Open Add New Item Screen through Solution Context Menu of Contact >> Add >> New Item >> Installed >> .NET Core >> MVC View Page.
- Name it CreateContact.cshtml.
- Click OK button.
- It will add a new view in Contact view folder.
- Now, we have ContactVM objects as a model.
- First of all, we have used form TagHelper to create a form and it will post to CreateContact action method of Controller by specifying asp-action="CreateContact".
- Div TagHelper is used to show the validation summary of all the fields.
- Label TagHelper is used to show the label field.
- Input TagHelper is used to bind input of the fields with the related fields.
- Span TagHelper is used to show an error message of the related fields.
- Anchor TagHelper to add the link to navigate to the main list page.
- A simple native input button of submit type to submit the form.
- Change Index view implementation to add Create Contact option.
- @model ContactVM
- <h2>Create Contact</h2>
- <form asp-action="CreateContact">
- <div class="form-horizontal">
- <div asp-validation-summary="ModelOnly" class="text-danger"></div>
- <div class="form-group">
- <label asp-for="ContactId" class="col-md-2 control-label"></label>
- <div class="col-md-10">
- <input asp-for="ContactId" class="form-control" disabled="disabled" />
- <span asp-validation-for="ContactId" class="text-danger" />
- </div>
- </div>
- <div class="form-group">
- <label asp-for="Name" class="col-md-2 control-label"></label>
- <div class="col-md-10">
- <input asp-for="Name" class="form-control" />
- <span asp-validation-for="Name" class="text-danger" />
- </div>
- </div>
- <div class="form-group">
- <label asp-for="Address1" class="col-md-2 control-label"></label>
- <div class="col-md-10">
- <input asp-for="Address1" class="form-control" />
- <span asp-validation-for="Address1" class="text-danger" />
- </div>
- </div>
- <div class="form-group">
- <label asp-for="Address2" class="col-md-2 control-label"></label>
- <div class="col-md-10">
- <input asp-for="Address2" class="form-control" />
- <span asp-validation-for="Address2" class="text-danger" />
- </div>
- </div>
- <div class="form-group">
- <label asp-for="City" class="col-md-2 control-label"></label>
- <div class="col-md-10">
- <input asp-for="City" class="form-control" />
- <span asp-validation-for="City" class="text-danger" />
- </div>
- </div>
- <div class="form-group">
- <label asp-for="ProvinceState" class="col-md-2 control-label"></label>
- <div class="col-md-10">
- <input asp-for="ProvinceState" class="form-control" />
- <span asp-validation-for="ProvinceState" class="text-danger" />
- </div>
- </div>
- <div class="form-group">
- <label asp-for="ZipPostalCode" class="col-md-2 control-label"></label>
- <div class="col-md-10">
- <input asp-for="ZipPostalCode" class="form-control" />
- <span asp-validation-for="ZipPostalCode" class="text-danger" />
- </div>
- </div>
- <div class="form-group">
- <label asp-for="Country" class="col-md-2 control-label"></label>
- <div class="col-md-10">
- <input asp-for="Country" class="form-control" />
- <span asp-validation-for="Country" class="text-danger" />
- </div>
- </div>
- <div class="form-group">
- <label asp-for="ContactNumber" class="col-md-2 control-label"></label>
- <div class="col-md-10">
- <input asp-for="ContactNumber" class="form-control" />
- <span asp-validation-for="ContactNumber" class="text-danger" />
- </div>
- </div>
- <div class="form-group">
- <label asp-for="Email" class="col-md-2 control-label"></label>
- <div class="col-md-10">
- <input asp-for="Email" class="form-control" />
- <span asp-validation-for="Email" class="text-danger" />
- </div>
- </div>
- <div class="form-group">
- <label asp-for="WebSite" class="col-md-2 control-label"></label>
- <div class="col-md-10">
- <input asp-for="WebSite" class="form-control" />
- <span asp-validation-for="WebSite" class="text-danger" />
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Create" class="btn btn-default" />
- </div>
- </div>
- </div>
- </form>
- <p>
- <a asp-action="Index">Back to List</a>
- </p>
- @model List<ContactListVM>
- <h2>Contact List</h2>
- <table class="table">
- <thead>...</thead>
- <tbody>...</tbody>
- </table>
- <p>
- <a asp-action="CreateContact">Create Contact</a>
- </p>
Run Application in Debug Mode
- Press F5 or Debug Menu >> Start Debugging or start IIS Express button on the toolbar to start the Application in the debugging mode.
- It will show Home Page in the Browser.
- Click Contact List Menu Open to open Contact List Page.
- Click Create Contact link to open Create Contact Page and URL will change to http://localhost:21840/Contact/CreateContact.
- Add contact data, click create button and it will add the contact in the list.
- It allows us to insert the contact with the incomplete or incorrect information.
Add Validation to Create Contact
- Add the required data annotation of the required string length, Email and WEB URL type.
- Add the script references to jquery-validation.js and jquery-validation-unobtrusive.js in the required view or in _Layout view. It is always recommended to include JavaScripts in the required views only, but for generic items we are going to include these in _Layout.
- Now run the Application and try to input the incorrect data or to miss the required data. It will not allow you to press create button. In this way, we not only achieve better user experience, but also make our data cleaner with few Server side hits.
- We will discuss the data validation in detail in future sessions.
- public class ContactVM
- {
- [Display(Name = "Contact Id")]
- public int ContactId { get; set; }
- [Required]
- [StringLength(100, MinimumLength = 3)]
- [Display(Name = "Contact Name")]
- public string Name { get; set; }
- [StringLength(100)]
- [Display(Name = "Address 1")]
- public string Address1 { get; set; }
- [StringLength(100)]
- [Display(Name = "Address 2")]
- public string Address2 { get; set; }
- [StringLength(100)]
- [Display(Name = "City")]
- public string City { get; set; }
- [StringLength(100)]
- [Display(Name = "Province/State")]
- public string ProvinceState { get; set; }
- [StringLength(10)]
- [Display(Name = "Zip/Postal Code")]
- public string ZipPostalCode { get; set; }
- [StringLength(100)]
- [Display(Name = "Country")]
- public string Country { get; set; }
- [Required]
- [StringLength(100, MinimumLength = 7)]
- [Display(Name = "Contact Number")]
- public string ContactNumber { get; set; }
- [EmailAddress]
- [StringLength(255)]
- [Display(Name = "Email")]
- public string Email { get; set; }
- [Url]
- [StringLength(100)]
- [Display(Name = "Web Site")]
- public string WebSite { get; set; }
- }
Run Application in Debug Mode Again
- Press F5 or Debug Menu >> Start Debugging or start IIS Express button on the toolbar to start the Application in the debugging mode.
- It will show Home Page in the Browser.
- Click Contact List Menu to open Contact List Page.
- Click Create Contact link to open Create Contact Page and URL will change to http://localhost:21840/Contact/CreateContact.
- Without adding any data, click Create button and it will show the errors for the required fields.
- Now, try to add zip code larger than 10 character or incorrect Email or Website. It will show you error messages.
- Now correct the data, click Create button and it will create contact.
Sample Source Code
We have placed sample code for this session in "CRUD operations in ASP.NET Core 1.0 MVC Application Part 4_Code.zip" in CodePlex repository.