MyContactBook : Part 4 - Add New Contact into Database

Steps :
Step - 1 : Add new Class for Implement Validation.

Right Click on Solution Explorer > Add > Class > Enter Class name > Add.

Step-2: Write the following code into the class for apply validation on model.
            using System;
            using System.Collections.Generic;
            using System.ComponentModel.DataAnnotations;
            using System.Linq;
            using System.Web;

            namespace MVCContactBook
            {
                public class ContactValidation
                {
                    [Display(Name="First Name")]
                    [Required(ErrorMessage="Please provide First Name", AllowEmptyStrings = false)]
                    public string ContactPersonFname { get; set; }

                    [Display(Name="Last Name")] // Its not required
                    public string ContactPersonLname { get; set; }

                    [Display(Name="Contact No1")]
                    [Required(ErrorMessage="Please provide Last Name", AllowEmptyStrings=false)]
                    public string ContactNo1 { get; set; }

                    [Display(Name = "Contact No2")]
                    public string ContactNo2 { get; set; }

                    [Display(Name="Email ID")]
                    [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", 
                        ErrorMessage="Email not valid")]
                    public string EmailID { get; set; }

                    [Display(Name="Country")]
                    [Required(ErrorMessage = "Please select country")]
                    public int CountryID { get; set; }

                    [Display(Name = "State")]
                    [Required(ErrorMessage = "Please select state")]
                    public int StateID { get; set; }
                }


                [MetadataType(typeof(ContactValidation))] // Apply validation
                public partial class Contact
                {

                }
            }
        
Step-3: Add new action into your controller for Get form (get Method) for Save Contact to database.

Here I have added "Add" Action into "Home" Controller. Please write this following code for the Action

            public ActionResult Add()
            {
                //fetch country data 
                List<Country> AllCountry = new List<Country>();
                List<State> states = new List<State>();
                // Here MyContactBookEntities is our DbContext
                using (MyContactBookEntities dc = new MyContactBookEntities())
                {
                    AllCountry = dc.Countries.OrderBy(a => a.CountryName).ToList();
                    //Not need to fetch state as we dont know which country will user select here
                }

                ViewBag.Country = new SelectList(AllCountry, "CountryID", "CountryName");
                ViewBag.State = new SelectList(states, "StateID", "StateName");

                return View();
            }
        
Step-4: Add a new Action into Controller for fetch States of the selected Country.

Here I have added "GetStates" Action into "Home" Controller for fetch States (json data) of the selected country from jquery (ajax) code. Here we will see how to implement casecade dropdown.
Please write this following code for the Action

"GetStates" Action Code
            
            public JsonResult GetStates(int countryID)
            {
                using (MyContactBookEntities dc = new MyContactBookEntities())
                {
                    //We will off Lazy Loading
                    var State = (from a in dc.States
                                 where a.CountryID.Equals(countryID)
                                 orderby a.StateName
                                 select a).ToList();
                    return new JsonResult { Data = State, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                }
            }
        
Step-5: Add view for the Action & design the form.

Right Click on Action Method (here right click on Add action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.

Html Code of the View
            
            @model MVCContactBook.Contact
            @{
                ViewBag.Title = "Add Contact";
            }

            <h2>Add</h2>

            @using (Html.BeginForm("Add", "Home", FormMethod.Post, new { @class="form-horizontal", enctype="multipart/form-data"} ))
            {
                @Html.ValidationSummary(true)
                @Html.AntiForgeryToken()     //we need this for prevent CSRF Attack

                //Here I will customize the form for good looks and support bootstrap responsive view (not mandatory)   
    
                    <div class="form-group">
                        @Html.LabelFor(model => model.ContactPersonFname, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.ContactPersonFname, new { @class="form-control", placeholder="Enter first name"})
                            @Html.ValidationMessageFor(model => model.ContactPersonFname)
                        </div>
                    </div>
        
                 //Same Way We will do all
                    <div class="form-group">
                        @Html.LabelFor(model => model.ContactPersonLname, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.ContactPersonLname, new { @class="form-control", placeholder="Enter last name"})
                            @Html.ValidationMessageFor(model => model.ContactPersonLname)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.ContactNo1, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.ContactNo1, new { @class="form-control", placeholder="Enter Contact No1"})
                            @Html.ValidationMessageFor(model => model.ContactNo1)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.ContactNo2, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.ContactNo2, new { @class="form-control", placeholder="Enter Contact No2"})
                            @Html.ValidationMessageFor(model => model.ContactNo2)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.EmailID, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.EmailID, new { @class="form-control", placeholder="Enter Email ID"})
                            @Html.ValidationMessageFor(model => model.EmailID)
                        </div>
                    </div>        
                    <div class="form-group">
                        @Html.LabelFor(model => model.CountryID, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.DropDownListFor(model => model.CountryID, @ViewBag.Country as SelectList,"Select Country", new { @class="form-control"})
                            @Html.ValidationMessageFor(model => model.CountryID)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.StateID, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.DropDownListFor(model => model.StateID, @ViewBag.State as SelectList,"Select State", new { @class="form-control"})
                            @Html.ValidationMessageFor(model => model.StateID)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Address, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextAreaFor(model => model.Address,3,5, new { @class="form-control", placeholder="Enter Address"})
                            @Html.ValidationMessageFor(model => model.Address)
                        </div>
                    </div>        
                    // Here Have to do for File 
                    <div class="form-group">
                        <label class="col-md-2 control-label">Select File : </label>
                        <div class="col-md-10">
                            @Html.TextBox("file", null, new { type="file", @class="form-control", placeholder="Enter Address", accept = "image/x-png, image/gif, image/jpeg"})
                            @Html.ValidationMessage("FileErrorMessage")
                        </div>            
                    </div>         
        
                   <div class="form-group">
                       <div class="col-md-10 col-md-offset-2">
                            <input type="submit" value="Create" class="btn btn-primary" />
                        </div>
                    </div>

            }

            <div>
                @Html.ActionLink("Back to List", "Index")
            </div>
        
Step-6: Write jquery code in View of Add Action for Implement casecade dropdown.
Jquery Code
            <script>
            //here we will fetch states for the selected country
            $(document).ready(function () {
                $('#CountryID').change(function () {
                
                    var countryID = parseInt($(this).val());
                
                    if (!isNaN(countryID)) {
                    
                        var $ddState = $('#StateID');
                        $ddState.empty(); // Clear all Items 
                        $ddState.append($("<option></option>").val('').html('Please Wait...'));

                        $.ajax({
                            url: '@Url.Action("GetStates","Home")',
                            type: 'GET',
                            dataType: 'json',
                            data: {countryID : countryID},
                            success: function (d) {
                                $ddState.empty(); // Clear all Items 
                                $ddState.append($("<option></option>").val('').html('Select State'));                            
                                $.each(d, function (i, item) {                                
                                    $ddState.append($("<option></option>").val(item.StateID).html(item.StateName));
                                });
                            },
                            error: function () {
                                alert('Error!');
                            }
                        });
                    }

                });
            });
        </script>
         
Complete View
            @model MVCContactBook.Contact
            @{
                ViewBag.Title = "Add Contact";
            }

            <h2>Add</h2>

            @using (Html.BeginForm("Add", "Home", FormMethod.Post, new { @class="form-horizontal", enctype="multipart/form-data"} ))
            {
                @Html.ValidationSummary(true)
                @Html.AntiForgeryToken()     //we need this for prevent CSRF Attack

                //Here I will customize the form for good looks and support bootstrap responsive view (not mandatory)   
    
                    <div class="form-group">
                        @Html.LabelFor(model => model.ContactPersonFname, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.ContactPersonFname, new { @class="form-control", placeholder="Enter first name"})
                            @Html.ValidationMessageFor(model => model.ContactPersonFname)
                        </div>
                    </div>
        
                 //Same Way We will do all
                    <div class="form-group">
                        @Html.LabelFor(model => model.ContactPersonLname, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.ContactPersonLname, new { @class="form-control", placeholder="Enter last name"})
                            @Html.ValidationMessageFor(model => model.ContactPersonLname)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.ContactNo1, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.ContactNo1, new { @class="form-control", placeholder="Enter Contact No1"})
                            @Html.ValidationMessageFor(model => model.ContactNo1)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.ContactNo2, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.ContactNo2, new { @class="form-control", placeholder="Enter Contact No2"})
                            @Html.ValidationMessageFor(model => model.ContactNo2)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.EmailID, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.EmailID, new { @class="form-control", placeholder="Enter Email ID"})
                            @Html.ValidationMessageFor(model => model.EmailID)
                        </div>
                    </div>        
                    <div class="form-group">
                        @Html.LabelFor(model => model.CountryID, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.DropDownListFor(model => model.CountryID, @ViewBag.Country as SelectList,"Select Country", new { @class="form-control"})
                            @Html.ValidationMessageFor(model => model.CountryID)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.StateID, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.DropDownListFor(model => model.StateID, @ViewBag.State as SelectList,"Select State", new { @class="form-control"})
                            @Html.ValidationMessageFor(model => model.StateID)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Address, new { @class="col-md-2 control-label"})
                        <div class="col-md-10">
                            @Html.TextAreaFor(model => model.Address,3,5, new { @class="form-control", placeholder="Enter Address"})
                            @Html.ValidationMessageFor(model => model.Address)
                        </div>
                    </div>        
                    // Here Have to do for File 
                    <div class="form-group">
                        <label class="col-md-2 control-label">Select File : </label>
                        <div class="col-md-10">
                            @Html.TextBox("file", null, new { type="file", @class="form-control", placeholder="Enter Address", accept = "image/x-png, image/gif, image/jpeg"})
                            @Html.ValidationMessage("FileErrorMessage")
                        </div>            
                    </div>         
        
                   <div class="form-group">
                       <div class="col-md-10 col-md-offset-2">
                            <input type="submit" value="Create" class="btn btn-primary" />
                        </div>
                    </div>

            }

            <div>
                @Html.ActionLink("Back to List", "Index")
            </div>

            @section Scripts {
                @Scripts.Render("~/bundles/jqueryval")
                <script>
                    //here we will fetch states for the selected country
                    $(document).ready(function () {
                        $('#CountryID').change(function () {
                
                            var countryID = parseInt($(this).val());
                
                            if (!isNaN(countryID)) {
                    
                                var $ddState = $('#StateID');
                                $ddState.empty(); // Clear all Items 
                                $ddState.append($("<option></option>").val('').html('Please Wait...'));

                                $.ajax({
                                    url: '@Url.Action("GetStates","Home")',
                                    type: 'GET',
                                    dataType: 'json',
                                    data: {countryID : countryID},
                                    success: function (d) {
                                        $ddState.empty(); // Clear all Items 
                                        $ddState.append($("<option></option>").val('').html('Select State'));                            
                                        $.each(d, function (i, item) {                                
                                            $ddState.append($("<option></option>").val(item.StateID).html(item.StateName));
                                        });
                                    },
                                    error: function () {
                                        alert('Error!');
                                    }
                                });
                            }

                        });
                    });
                </script>
            }

        
Step-7: Add new action into your controller for Post form (POST Method) for Save Contact to database.

Here I have added "Add" Action with Model Parameter (here "Contact") into "Home" Controller. Write this following code

            
            
        
Step-8: Run Application.
MyContactBook : Part 4 - Add New Contact into Database
Posted By :