Creating ASP.NET MVC 5 Application using Entity Framework 6 and Identity with CRUD Operations on visual studio 2015 Part-8

This is the part-8 of asp.net mvc 5 series using entity framework and identity from scratch.In this tutorial you will learn how to make a server side validation using asp.net mvc data-annotation? How to make a partial class of  entity model class? So there is a complete step by step process of making patient registration form, if you have any query regarding this tutorial, please comment right below and your query will be answered as soon as possible. Other part of series: 

  1. Creating ASP.NET MVC 5 project Part-1?
  2. Creating SQL Server database Part-2?
  3. Creating Entity Framework project Part-3 ?
  4. Customize the default template of ASP.NET MVC 5 Part-4 ?
  5. How to add a controller and view Part-5 ?
  6. How to Add Model Part-6 ?
  7. How to make a patient registration form Part-7?

  • MVC Data Annotations for Model Validation
    • In the development of web application data validation is a key aspect.We can easily apply validation to web application by using  data annotations attribute classes to model in asp.net mvc 5.Data Annotation attribute classes are present in System.ComponentModel.DataAnnotations namespace and are availlable to Asp.net projects like Asp.net web application & website, Asp.net MVC, Web forms and also to Entity framework ORM models.Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users.
    • Data Annotations validator attribute:
      • DataTypeSpecify the data type of a property.
      • DisplayNameSpecify the display name for a property.
      • DisplayFormat: Specify the display format for a property like different format for date property.
      • Required:Specify a property as required.
      • RegularExpressionValidate the value of property by specified regular expression pattern.
      • RangeValidate the value of a property with in specified value of range.
      • StringLength: Specify min and max length for string property.
      • MaxLengthSpecify the max length for the string property.
      • Bind:SpecifySpecify fields to include or exclude when adding parameter or form values to model properties. 
      • ScaffoldColumnSpecify fields for hiding form editor forms.
  • MVC Data Annotations for Model Validation
    • We have created a patient form in part-7, just  run the application and see the output of patient form in browser. you will see the following output:
    • Now if you hit the save button you will see the following error page.
    • To remove this error just add link of the jquery.validate.js, jquery.validate.unobtrusive.js and jquery.unobtrusive-ajax.js files from script folder just like that:
    • Now create a Validation folder in HIMS.Model project and create a validation class Make a tblPatient partial class in HIMS.Model  and define the label display name as well as required filed attribute by using DataAnnotations class.Let's create a validation class, right on the validation folder in HIMS.Model project and go to Add > Class, enter the name of class Validation and finally click Ok. Your validation class is created and replace the whole code with the following code.
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.ComponentModel.DataAnnotations;
      namespace HIMS.Model
      {
          [MetadataType(typeof(tblPatient.Patient))]
          public partial class tblPatient
          {
              sealed class Patient
              {   
                  public string MRN { get; set; }

                  [Required]
                  [Display(Name ="First Name:")]
                  public string FName { get; set; }
                  [Display(Name ="Middle Name:")]
                  public string MName { get; set; }
                  [Required]
                  [Display(Name ="Last Name:")]
                  public string LName { get; set; }
                  public string Gender { get; set; }
                  [Display(Name ="Date of birth:")]
                  public Nullable<System.DateTime> DOB { get; set; }
                  [Display(Name ="Marital Status:")]
                  public string Marital_Status { get; set; }
                  [Display(Name ="Select country:")]
                  public Nullable<int> CountryId { get; set; }
                  [Display(Name ="Select province"")]
                  public Nullable<int> ProvinceId { get; set; }
                  [Display(Name ="Select district:")]
                  public Nullable<int> DistrictId { get; set; }
                  [Display(Name ="Select city:")]
                  public Nullable<int> CityId { get; set; }
                  [Display(Name ="Primary address:")]
                  public string PrimaryAddress { get; set; }
                  [Display(Name ="Secondary address:")]
                  public string SecondaryAddress { get; set; }
                  [Display(Name ="Mobile #:")]
                  public string MobilePhone { get; set; }
                  [Display(Name ="Work phone #:")]
                  public string WorkPhone { get; set; }
              }
          }
      }
    • Your validation class just looks like this.
    • Finally run the application and in the patient form hit the save button you can see all data annotations is applied.You can apply all the data annotations attributes and you can change the error massage as you want.
  • SummaryIn this article I try to expose the Data Annotations with example. I hope you will understand. I would like to have feedback from my blog readers. Please post your  comments about this article.

xt »

Creating ASP.NET MVC 5 Application using Entity Framework 6 and Identity with CRUD Operations on visual studio 2015 Part-7

This is the part-7 of asp.net mvc 5 series using entity framework and identity from scratch.In this tutorial we will make a tightly bound patient registration form using razor engine.Also includes how to update the entity model from database? and how to select the data from database using entity framework? So there is a complete step by step process of making patient registration form.If you have any query regarding this tutorial, please comment right below and your query will be answered as soon as possible. Other part of series: 
  1. Creating ASP.NET MVC 5 project Part-1?
  2. Creating SQL Server database Part-2?
  3. Creating Entity Framework project Part-3 ?
  4. Customize the default template of ASP.NET MVC 5 Part-4 ?
  5. How to add a controller and view Part-5 ?
  6. How to Add Model Part-6 ?

  1. How to make a patient registration form?

    1. Update the entity model from database?
      1. First of all there is a change in database table name from patient to tblpatient due to namespace issue of patient class, so please change the name of table first by right click on the table name in sql server and rename it.How to update the entity model from database in asp.net mvc 5? Let's update the entity model, open the HIMS.Model.edmx diagram and right click anywhere in the .edmx diagram and go to update model from database option.e.g
      2. Pop-up window will appear, just checked the table checkbox and click on the finish button.
      3. Your model is updated with the latest table name tblpatient. e.g
    2. Model property & drop-down select list binding?
      1. For making tightly bound patient registration form, initialize the patient model class and drop-down select list in RegistrationViewModel first or copy and paste the following code in your RegistrationViewModel.e.g
      2. Code:
        using HIMS.Model;
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.Mvc;
        namespace HIMS.Patient.Registration.Models
        {
           public class RegistrationViewModel
              {
                   public tblPatient patient { get; set; }
                   public SelectList genderList { get; set; }
                   public SelectList martialStatusList { get; set; }
                   public SelectList countryList { get; set; }
                   public SelectList provinceList { get; set; }
                   public SelectList districtList { get; set; }
                   public SelectList cityList { get; set; }
              }
        }
    3. Binding a view with ViewModel?
      1. Initialize the RegistrationViewModel in your patient form/view and make a patient registration form or html with razor engine syntax tightly bound with the RegistrationViewModel.e.g
      2. Copy & paste the following code in your Patient view.
        @model HIMS.Patient.Registration.Models.RegistrationViewModel
        @{
            ViewBag.Title = "Patient";
        }
        <style>
            input, select, textarea {
                max-width: 100%;
            }
        </style>
        <div class="col-md-12">
            @using (Ajax.BeginForm("savePatient", "Patient", null, new AjaxOptions
            {
                HttpMethod = "POST",
                OnSuccess = "SucessCallBack(data)",
                OnFailure = "FailureCallBack(data)"
            }, new { id = "patientForm" }))
            {
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <div class="panel-title">
                            Patient Registration
                        </div>
                    </div>
                    <div class="panel-body">
                        <div class="col-md-12">
                            <div class="col-md-4">
                                <div class="form-group">
                                    @Html.LabelFor(x => x.patient.FName)
                                    @Html.TextBoxFor(x => x.patient.FName, new { @class = "form-control" })
                                    @Html.ValidationMessageFor(x => x.patient.FName, null, new { @class = "ErrorMsg" })
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    @Html.LabelFor(x => x.patient.MName)
                                    @Html.TextBoxFor(x => x.patient.MName, new { @class = "form-control" })
                                    @Html.ValidationMessageFor(x => x.patient.MName, null, new { @class = "ErrorMsg" })
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    @Html.LabelFor(x => x.patient.LName)
                                    @Html.TextBoxFor(x => x.patient.LName, new { @class = "form-control" })
                                    @Html.ValidationMessageFor(x => x.patient.LName, null, new { @class = "ErrorMsg" })
                                </div>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="col-md-6">
                                <div class="form-group">
                                    @Html.LabelFor(x => x.patient.Gender)
                                    @Html.DropDownListFor(x => x.patient.Gender, Model.genderList, "--Select gender--", new { @class = "form-control" })
                                    @Html.ValidationMessageFor(x => x.patient.Gender, null, new { @class = "ErrorMsg" })
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    @Html.LabelFor(x => x.patient.Marital_Status)
                                    @Html.DropDownListFor(x => x.patient.Marital_Status, Model.martialStatusList, "--Select gender--", new { @class = "form-control" })
                                    @Html.ValidationMessageFor(x => x.patient.Marital_Status, null, new { @class = "ErrorMsg" })
                                </div>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="col-md-6">
                                <div class="form-group">
                                    @Html.LabelFor(x => x.patient.PrimaryAddress)
                                    @Html.TextAreaFor(x => x.patient.PrimaryAddress, new { @class = "form-control" })
                                    @Html.ValidationMessageFor(x => x.patient.PrimaryAddress, null, new { @class = "ErrorMsg" })
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    @Html.LabelFor(x => x.patient.SecondaryAddress)
                                    @Html.TextAreaFor(x => x.patient.SecondaryAddress, new { @class = "form-control" })
                                    @Html.ValidationMessageFor(x => x.patient.SecondaryAddress, null, new { @class = "ErrorMsg" })
                                </div>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="col-md-3">
                                <div class="form-group">
                                    @Html.LabelFor(x => x.patient.CountryId)
                                    @Html.DropDownListFor(x => x.patient.CountryId, Model.countryList, "--Select country--", new { @class = "form-control" })
                                    @Html.ValidationMessageFor(x => x.patient.CountryId, null, new { @class = "ErrorMsg" })
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    @Html.LabelFor(x => x.patient.ProvinceId)
                                    @Html.DropDownListFor(x => x.patient.ProvinceId, Model.provinceList, "--Select province--", new { @class = "form-control" })
                                    @Html.ValidationMessageFor(x => x.patient.ProvinceId, null, new { @class = "ErrorMsg" })
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    @Html.LabelFor(x => x.patient.DistrictId)
                                    @Html.DropDownListFor(x => x.patient.DistrictId, Model.districtList, "--Select district--", new { @class = "form-control" })
                                    @Html.ValidationMessageFor(x => x.patient.DistrictId, null, new { @class = "ErrorMsg" })
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    @Html.LabelFor(x => x.patient.CityId)
                                    @Html.DropDownListFor(x => x.patient.CityId, Model.cityList, "--Select city--", new { @class = "form-control" })
                                    @Html.ValidationMessageFor(x => x.patient.CityId, null, new { @class = "ErrorMsg" })
                                </div>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="col-md-2 pull-right">
                                <input type="submit" id="savebtn" class="btn btn-primary pull-right" value="Save"  />
                            </div>
                        </div>
                    </div>
                </div>
            }
        </div>
    4. Adding a RegistrationMethod model class?
      1. This is model class contains all the methods of crud operations.Basically designed for the communication with the database entities directly.You can directly communicate with database entities in the controller action result also but i have created a separate class for making things easy. Let's create a RegistrationMethod class, right click on Models folder and go to Add > Class.Pop-up window will appear and enter the name of class RegistrationMethods.cs and click to Add button.
      2. Your RegistrationMethods class is created, copy & paste the following code in your RegistrationMethods class.
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using HIMS.Model;
        using System.Web.Mvc;

        namespace HIMS.Patient.Registration.Models
        {
            public class RegistrationMethods
            {
                Entities db = new Entities();
                public SelectList genderList()
                {
                    List<SelectListItem> genderlistitem = new List<SelectListItem>();
                    genderlistitem.Add(new SelectListItem { Text = "Male", Value = "Male" });
                    genderlistitem.Add(new SelectListItem { Text = "Female", Value = "Female" });
                    return new SelectList(genderlistitem, "Value", "Text");
                }
                public SelectList martalStatusList()
                {
                    List<SelectListItem> maritalstatuslistitem = new List<SelectListItem>();
                    maritalstatuslistitem.Add(new SelectListItem { Text = "Single", Value = "Single" });
                    maritalstatuslistitem.Add(new SelectListItem { Text = "Married", Value = "Married" });
                    return new SelectList(maritalstatuslistitem, "Value", "Text");
                }
                public SelectList countryList()
                {
                    List<Country> countryList= db.Countries.ToList();
                    List<SelectListItem> countrylistitem = new List<SelectListItem>();
                    foreach (var x in countryList)
                    {
                        countrylistitem.Add(new SelectListItem { Text = x.Name.ToString(), Value = x.CountryID.ToString() });
                    }
                    return new SelectList(countrylistitem, "Value", "Text");
                }
                public SelectList provinceList(int countryId)
                {
                    List<Province> provinceList = db.Provinces.Where(x=>x.CountryId==countryId).ToList();
                    List<SelectListItem> provincelistitem = new List<SelectListItem>();
                    foreach (var x in provinceList)
                    {
                        provincelistitem.Add(new SelectListItem { Text = x.Name.ToString(), Value = x.Id.ToString() });
                    }
                    return new SelectList(provincelistitem, "Value", "Text");
                }
                public SelectList districtList(int provinceId)
                {
                    List<District> districtList = db.Districts.Where(x=>x.ProvinceId==provinceId).ToList();
                    List<SelectListItem> districtlistitem = new List<SelectListItem>();
                    foreach (var x in districtList)
                    {
                        districtlistitem.Add(new SelectListItem { Text = x.Name.ToString(), Value = x.Id.ToString() });
                    }
                    return new SelectList(districtlistitem, "Value", "Text");
                }
                public SelectList cityList(int districtId)
                {
                    List<City> citylList = db.Cities.Where(x => x.DistrictId == districtId).ToList();
                    List<SelectListItem> citylistitem = new List<SelectListItem>();
                    foreach (var x in citylList)
                    {
                        citylistitem.Add(new SelectListItem { Text = x.Name.ToString(), Value = x.Id.ToString() });
                    }
                    return new SelectList(citylistitem, "Value", "Text");
                }
            }
        }
    5. Update the Registration Controller?
      1. Update the Patient action method, bind the RegistrationMethods class with the RegistrationViewModel or assigning the RegistrationMethods result to ViewModel.Let's copy & paste the following code in your Registration controller.
        using HIMS.Patient.Registration.Models;
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.Mvc;
        namespace HIMS.Patient.Registration.Controllers
        {
            public class RegistrationController : Controller
            {
                // GET: Registration
                public ActionResult Patient()
                {
                   try
                    {
                       
                        RegistrationViewModel model = new RegistrationViewModel();
                        RegistrationMethods method = new RegistrationMethods();
                        List<SelectListItem> emptyList = new List<SelectListItem>();

                        model.genderList = method.genderList();
                        model.martialStatusList = method.martalStatusList();
                        model.countryList = method.countryList();
                        model.provinceList = new SelectList(emptyList);
                        model.districtList = new SelectList(emptyList);
                        model.cityList = new SelectList(emptyList);
                        return View(model);
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }
        }
        }
    6. Patient Registration Form?
      1. Your patient registration form is ready, you can run the application by just click on the run button.
      2. Patient form looks like the following diagram.e.g


Next »

Creating ASP.NET MVC 5 Application using Entity Framework 6 and Identity with CRUD Operations on visual studio 2015 Part-6


This is the part-6 of asp.net mvc 5 series using entity framework and identity from scratch.What is model and view model ?How we add a reference of one project to another project? Other part of series,
  1. Creating ASP.NET MVC 5 project Part-1?
  2. Creating SQL Server database Part-2?
  3. Creating Entity Framework project Part-3 ?
  4. Customize the default template of ASP.NET MVC 5 Part-4 ?
  5. How to add a controller and view Part-5 ?
  6. How to Add Model Part-6 ?
  7. How to make a patient registration form Part-7?
  1. How to add a Model?

    1. Model is a logical part of application which communicate with the database entities.Our model is already created which is database entity model or entity framework model now we are just creating a RegistrationViewModel class which contains the initialization of database entities model.View Model (just like a class) is created because when multiple entities are used in a single view then we bind the view with view model.For example in patient registration page/form we want to display the patient list also then we need two things, one is patient object initialization and other is patient list.So these two patient and patient list objects are initialized in the view model and we tightly bind the view with view model.First create a model class or (view model class) by right clicking on the model folder and go to Add > Class.
    2. Pop-up window will appear, just select the Class and the enter the name of class RgistrationViewModel.cs and click Add button.
    3. Your RegistrationViewModel class is created.e.g
    4. Now initialize the patient entity model from the entity framework model namespace  or [HIMS.Model].So we are first adding a reference of HIMS.Model project to HIMS.Patient.Registration project.
    5. Pop-up window will appear and under Projects > Solution  check HIMS.Model project and click OK.
    6. HIMS.Model project reference is added to your project.Now include the namespace of HIMS.Model (using HIMS.Model) to RegistrationViewModel class and initialize the patient object by get and set property.

    7. In the next post we will make a patient registration form tightly bound with the RegistrationViewModel using razor engine. If you have any query the regarding the asp.net mvc, please feel free and post a comment right blow. Thank you   

Creating ASP.NET MVC 5 Application using Entity Framework 6 and Identity with CRUD Operations on visual studio 2015 Part-5

This is the part-5 of creating  ASP.NET MVC 5 application using entity framework 6.x and identity in visual studio 2015. This includes a overview of ASP.NET MVC with the project layout description. Also, how to add a controller and view in ASP.NET MVC project. If you have any query please feel free and post a comment right below, your query will be answered as soon as possible . Other part of series:
  • How to add a controller and view ?

    • ASP.NET MVC Overview

      •  MVC (Model-View-Controller) is a architectural pattern as well as design pattern which divides the application into three separate layers Model, View and Controller.ASP.NET MVC  is a replacement of web forms but in MVC there is no a page behind code.In MVC one controller has multiple views and one shared view can be used in multiple controller.So in the view there is simple html content or user interface material, In controller there are action methods  that renders the html.Model basically a logical part of application that communicates with the database entities.So basic diagram of MVC is as follow.
      • In ASP.NET MVC 5 default template each and every folder have its own purpose. So let's understand the basic purpose of folder in diagram given below.

    • Adding a Registration controller

      • :Learn how to create a  controller? Let's create a  Registration controller .Right click on the controller folder and go to Add Controller.
    • In Add scaffold window select the empty controller and click to Add button right below.
    • Enter the name of controller in pop-up window.
    • Your controller is created with default action method Index and you can see the same folder is created in the views folder.e.g
  • Adding a Patient view 

    • Right click on the Patient action result method and go to Add View.
    • View name and action result name should be same in the pop-up window  and in the template drop down you have multiple template option of binding a view with your model class.I will explain here only empty template if you guy's ask me to explain other template option then i will explain in the new post.Make sure reference script libraries and use a layout page is checked.Finally click on the add button.  
    • Your patient view is created with default patient title heading.Make sure your patient view tab is selected just like below in the diagram and then click on the run button. 
    • You will see the following output in the browser window with URL localhost:port#/Registration/Patient.
    • If you change the URL like this localhost:49693 and press the enter. You will see the following error if you deleted the HomeController and Home view folder.
    • Now just open RouteConfig.cs file from App_start folder and change the  route from Home controller to Registration and Index action method to Patient. After save just click on the run button.
    • Now you will see there is no error with root URL localhost:port# .

Creating ASP.NET MVC 5 Application using Entity Framework 6 and Identity with CRUD Operations on visual studio 2015 - Part -4

This is the part-4 of creating  asp.net mvc 5 application using entity framework 6.x and identity in visual studio 2015. In this tutorial you will learn how to customize the asp.net mvc 5  default template. If you have any query please feel free and post a comment right below. Other part of series:

  1. Creating ASP.NET MVC 5 project Part-1?
  2. Creating SQL Server database Part-2?
  3. Creating Entity Framework project Part-3 ?
  4. Customize the default template of ASP.NET MVC 5 Part-4 ?
  5. How to add a controller and view Part-5 ?
  6. How to Add Model Part-6 ?
  7. How to make a patient registration form Part-7?
    • Customize the default template of ASP.NET MVC 5

      • Open _Layout.cshtml from the shared folder. You can resign the whole layout html which you want to display on each and every page of your application. In layout page there is a nav bar or menu bar and render body area that specify the point at which the content from the child view is rendered relative to the layout defined. When you add a controller in the controller folder then a folder with same name of controller is created in the views folder. So all the get action method initially communicate with the same folder name if the render view is  not found then it goes to the shared folder and return the html.You can see diagram given below and hope you will understand the communication of controller with views folder as well as shared. 
      • Remove the HomeController and Home folder from views.Edit the title and remove the links (about & contact) from the nav bar.
      • After modify the layout page you can can run your application by click on the run button.
      • You  will see the following error message because of removing the  HomeController and Home folder from the views.This error will be removed by creating a controller and view as well as by redefining the Route in RouteConfig.cs file.So let's create a controller and view.

Creating ASP.NET MVC 5 Application using Entity Framework 6 and Identity with CRUD Operations on visual studio 2015 - Part-3

This is the part-3 of asp.net mvc 5 series. In this tutorial you will learn how to create your entity framework model as well as SQL server database connectivity with entity framework model.Also  learn how to create a multiple project in one solution. If you have any query please feel free and post a comment right below. Other part of series,

  1. Creating ASP.NET MVC 5 project Part-1?
  2. Creating SQL Server database Part-2?
  3. Creating Entity Framework project Part-3 ?
  4. Customize the default template of ASP.NET MVC 5 Part-4 ?
  5. How to add a controller and view Part-5 ?
  6. How to Add Model Part-6 ?
  7. How to make a patient registration form Part-7?
  • Creating your entity framework model

    • Let's create ASP.NET MVC 5 empty project in HIMS solution with name HIMS.Model. So right click on the HIMS solution and go to Add New Project.
    • In the add new project window  go to Installed> Visual C #> Web.  Select the ASP.NET Web Application and enter the name of project HIMS.Model and click OK. 
    • Pop-up window will be appear and select the empty template from the template window. Finally click OK.
    • Your empty project is created successfully. Here you can see there is a two projects in a single solution.
    • Now learn how to add entity model in the project? Let's add the entity model in HIMS.Model project by right clicking on the HIMS.Model project and go to Add > New item.
    • In the pop-up window go to Installed > Visual C# > Data > ADO.Net Entity Data  Model  and enter the name of entity model HIMS.Patient.Model then click Add.
    • Select the EF Designer from database  model from the Entity data model wizard window and click next.
    • Choose the Microsoft SQL Server data source  from data source window and click continue.
    • In connection properties window select the server name if not found then click on the refresh button.In connect to database panel select or enter the database name HIMS.DB and then click  OK.
    • Entity data model wizard window will be appear and you can see your connection string is created successfully and click next.
    • Choose the entity framework version from the pop-up window Entity Framework 6.x and click next.
    • From the pop-up window choose the database objects and settings which you want to include in your model.Finally click on the finish.
    • Congratulations! your entity model is created successfully.
    • Now you can see the whole project structure like this.
  • In the part-4 you will learn how to customize the default template of asp.net mvc 5.

Creating ASP.NET MVC 5 Application using Entity Framework 6 and Identity with CRUD Operations on visual studio 2015 Part-9

This is the part-9 of asp.net mvc 5 series using entity framework and identity from scratch.In this tutorial you will learn how to bind a...