Sunday, 4 September 2016

CRUD operations in ASP.NET Core 1.0 MVC Application Part 4

Let’s add Create Contact page for our Contacts. Instead of creating a new View Model, we will existing ContactVM but we will do some amendments for purpose of validation. We are going to extend our application from last discussion  CRUD operations in ASP.NET Core 1.0 MVC Application Part 3.

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.
    • One CreateContact method with no parameter and HttpGet attribute to explicitly specify that this is get method. It will be used to initialize and create a Create Page. We will pass view an empty ContactVM.
    • Other CreateContact method with parameter of ContactVM  type and HttpPost attribute to explicitly specify that this is post method. It will be used to validate inpute at server side and to create object.
      • Post method may use ModelState.IsValid property to check if model does not have any error. 
      • Transform ContactVM object to Contact object and pass it to ContactBusinessLogic().CreateContact for further processing.
      • If no error is found then we have performed all activities successfully, then we can move to other page, for example, in our case we may navigate to main list page. Alternatively, we may return the same view with current object for reprocessing.
    • It is not required to have both methods same name, but it is conventional and 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 model.
    • First of all we have used form TagHelper to create form and it will post to CreateContact action method of Controller by specifying asp-action="CreateContact".
    • Div TagHelper is used to show validation summary of all fields.
    • Label TagHelper is used to show label field.
    • Input TagHelper is used to bind input fields with related fields.
    • Span TagHelper is used to show error message of related fields.
    • Anchor TagHelper to add link to navigate to main list page.
    • And 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 Toolbar to start application in debugging mode.
  • It will show Home Page in 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 and click Create Button and it will add contact in the list.
  • Even, it allow us to insert contact with incomplete or incorrect information.

Add Validation to Create Contact

  • Add required data annotation of Required, String Length, Type like Email and WEB Url type.
  • Add Script References to jquery-validation.js and jquery-validation-unobtrusive.js in required view or in _Layout view. It is always recommended to include JavaScripts in required views only, but for generic items we are going include these in _Layout.
  • Now run Application, and try to input incorrect data or to miss 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 fewer server side hits.
  • Please refer ASP.NET Core 1.0 MVC Model for more details about Data Annotation.
  • We will discuss 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 Toolbar to start application in debugging mode.
  • It will show Home Page in 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.
  • Without adding any data and click Create Button and it will show errors for required fields.
  • Now, try to add zip code larger than 10 character or incorrect email and or web site. It will show you error messages.
  • Now correct data and click Create Button and it will create contact.

No comments:

Post a Comment