Sunday 8 October 2017

Implementing server site validation in Angular js

Web Api Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace WebApplication2.Models
{
    public class EMPVM
    {
        [Required(ErrorMessage="Eid should not be blank.")]
        public int? EID { get; set; }
        [Required(ErrorMessage="Name should not be blank.")]
        public string NAME { get; set; }
    }
}

Api Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    [RoutePrefix("api/Empservice")]
    public class EmpserviceController : ApiController
    {
        [HttpGet]
        [Route("Emps")]
        public IHttpActionResult Emps()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.EMPs.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
           
        }
        [HttpGet]
        [Route("Emp/{EID:int}", Name="Emp")]
        public IHttpActionResult Emp(int EID)
        {
            try
            {
                using(Database1Entities obj=new Database1Entities())
                {
                    return Ok(obj.EMPs.SingleOrDefault(m => m.EID == EID));
                }
                
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpPost]
        [Route("Save")]
        public IHttpActionResult Save(EMPVM VM)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (Database1Entities obj = new Database1Entities())
                    {
                        EMP emp = new EMP();
                        emp.EID = VM.EID??0;
                        emp.NAME = VM.NAME;
                        obj.EMPs.Add(emp);
                        obj.SaveChanges();
                        return Created(new Uri(Url.Link("Emp", new { EID = VM.EID })), "Data Saved.");
                    }
                }
                else
                {
                    return BadRequest(ModelState);
                }
                
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpPut]
        [Route("Update/{EID:int}")]
        public IHttpActionResult Update([FromUri]int EID,[FromBody]EMPVM VM)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (Database1Entities obj = new Database1Entities())
                    {
                        EMP emp = obj.EMPs.Find(EID);
                        emp.NAME = VM.NAME;
                        obj.SaveChanges();
                        return Ok("Data Updated.");
                    }
                }
                else
                {
                    return BadRequest(ModelState);
                }

            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpDelete]
        [Route("Delete/{EID:int}")]
        public IHttpActionResult Delete(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    EMP emp = obj.EMPs.Find(EID);
                    obj.EMPs.Remove(emp);
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }

            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

    }
}

Angular js code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="angular.js"></script>
    <link href="bootstrap.css" rel="stylesheet" />
    <link href="bootstrap-theme.css" rel="stylesheet" />
</head>
<body ng-app="app" ng-controller="Ctrl" style="padding-top:5px">
    <div class="container">
        <form class="form-horizontal">
            <div class="form-group">
                <label class="control-label col-lg-4">EID</label>
                <div class="col-lg-4">
                    <input type="text" class="form-control" ng-model="EMP.EID" />
                    <span style="color:red" ng-bind="errEID"></span>
                    
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-lg-4">NAME</label>
                <div class="col-lg-4">
                    <input type="text" class="form-control" ng-model="EMP.NAME" />
                    <span style="color:red" ng-bind="errNAME"></span>
                    
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-lg-4"></label>
                <div class="col-lg-4">
                    <input type="button" value="Save" style="width:80px" ng-click="save()" class="btn btn-primary" />
                    <input type="button" value="Update" style="width:80px" ng-click="update()" class="btn btn-primary" />
                    <input type="button" value="Reset" style="width:80px" ng-click="reset()" class="btn btn-primary" />
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-lg-4">SEARCH</label>
                <div class="col-lg-4">
                        <input type="text" ng-model="search.NAME" class="form-control"  placeholder="Search..." />
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="control-label col-lg-4"></label>
                <div class="col-lg-4">
                    <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
                        <thead class="bg-primary">
                            <tr>
                                <th>EID</th>
                                <th>NAME</th>
                                <th>UPDATE</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr ng-repeat="c in list|filter:search">
                                <td>{{c.EID}}</td>
                                <td>{{c.NAME}}</td>
                                <td>
                                    <a ng-click="edit(c.EID)">Edit</a>|
                                    <a ng-click="del(c.EID)">Delete</a>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </form>
    </div>
    <script type="text/javascript">
        angular.module("app", [])
        .controller("Ctrl", function ($scope, Empfactory) {
            function CLR() {
                $scope.errEID = "";
                $scope.errNAME = "";
                $scope.EMP = new emp();
            } CLR();
            function fill() {
                Empfactory.Gets().then(function (promise) {
                    $scope.list = promise.data;
                });
            } fill();
            $scope.save = function ()
            {
                Empfactory.Post($scope.EMP).error(function (response) {
                    if (response.ModelState["VM.EID"] != "")
                        $scope.errEID = response.ModelState["VM.EID"];
                    else
                        $scope.errEID = "";
                    if (response.ModelState["VM.NAME"] != "")
                        $scope.errNAME = response.ModelState["VM.NAME"];
                    else
                        $scope.errNAME = "";
                }).then(function (promise) {
                    alert(promise.data);
                    fill();
                    CLR();
                });
            }
            $scope.edit = function (EID)
            {
                Empfactory.Get(EID).then(function (promise) {
                    $scope.EMP = promise.data;
                });
            }
            $scope.update = function () {
               
                Empfactory.Put($scope.EMP).error(function (response) {
                    if (response.ModelState["VM.EID"] != "")
                        $scope.errEID = response.ModelState["VM.EID"];
                    else
                        $scope.errEID = "";
                    if (response.ModelState["VM.NAME"] != "")
                        $scope.errNAME = response.ModelState["VM.NAME"];
                    else
                        $scope.errNAME = "";
                }).then(function (promise) {
                    alert(promise.data);
                    fill();
                    CLR();
                });
            }
            $scope.reset = function ()
            {
                CLR();
            }
            $scope.del = function (EID)
            {
                if (confirm('Do you want to delete it ?'))
                {
                    Empfactory.Delete(EID).then(function (promise) {
                        alert(promise.data);
                        fill();
                    });
                }
            }

        })
        .factory("Empfactory", function ($http) {
            var fac = {};
            fac.Gets = function () {
                return $http.get("http://localhost:55683/api/Empservice/Emps");
            }
            fac.Get = function (EID) {
                return $http.get("http://localhost:55683/api/Empservice/Emp/" + EID);
            }
            fac.Post = function (EMP) {
                return $http.post("http://localhost:55683/api/Empservice/Save", EMP);
            }
            fac.Put = function (EMP) {
                
                return $http.put("http://localhost:55683/api/Empservice/Update/" + EMP.EID, EMP);
            }
            fac.Delete = function (EID) {
                return $http.delete("http://localhost:55683/api/Empservice/Delete/" + EID);
            }
            return fac;
        });
        function emp() {
            return {
                EID: null,
                NAME: null
            }
        }
    </script>

</body>
</html>


Example of HttpClient

public List<ErrorDetail> CreateDocumentUDF(int registrationDocumentId, DocumentUDF documentUDF)
        {
            //Form the appropriate request uri for this call
            var requestUri = String.Format("{1}CreateDocumentUDF?registrationDocumentId={0}", registrationDocumentId, serviceUri);

            //Make the get call to web service layer
            HttpResponseMessage serviceResponse =
                Task<HttpResponseMessage>.Run(async () => { return await mdsClient.PostAsJsonAsync(requestUri, documentUDF); }).Result;
            //Asses the status code and return
            switch (serviceResponse.StatusCode)
            {
                case HttpStatusCode.Created:
                    //The call was successful, deserialize the response to a Property Document list
                    documentUDF = serviceResponse.Content.ReadAsAsync<DocumentUDF>().Result;
                    //No errors so return null
                    return null;
                default:
                    //if call have Error, deserialize the error list and return
                    documentUDF = null;
                    return serviceResponse.Content.ReadAsAsync<List<ErrorDetail>>().Result;
            }

        }

  public List<ErrorDetail> UpdateDocumentUDF(int registrationDocumentId, DocumentUDF documentUDF)
        {
            //Form the appropriate request uri for this call
            var requestUri = String.Format("{1}UpdateDocumentUDF?registrationDocumentId={0}", registrationDocumentId, serviceUri);
            //Asses the status code and return
            HttpResponseMessage serviceResponse =
                Task<HttpResponseMessage>.Run(async () => { return await mdsClient.PutAsJsonAsync(requestUri, documentUDF); }).Result;
            switch (serviceResponse.StatusCode)
            {
                case HttpStatusCode.NoContent:
                    //The call was successful, deserialize the response to a RegistrationDistrict list
                    documentUDF = serviceResponse.Content.ReadAsAsync<DocumentUDF>().Result;
                    //No errors so return null
                    return null;

                default:
                    //if call have Error, deserialize the error list and return
                    documentUDF = null;
                    return serviceResponse.Content.ReadAsAsync<List<ErrorDetail>>().Result;
            }

        }

public List<ErrorDetail> DeleteDocumentUDF(int registrationDocumentId, int documentUDFMappingId)
        {
            //Form the appropriate request uri for this call
            var requestUri = String.Format("{2}DeleteDocumentUDF?registrationDocumentId={0}&documentUdfMappingId={1}", registrationDocumentId, documentUDFMappingId, serviceUri);
            //Make the get call to web service layer
            HttpResponseMessage serviceResponse =
               Task<HttpResponseMessage>.Run(async () => { return await mdsClient.DeleteAsync(requestUri); }).Result;
            //Asses the status code and return
            switch (serviceResponse.StatusCode)
            {
                //The call was successful, deserialize the response to a Zone list
                //No errors so return null
                case HttpStatusCode.NoContent:
                    return null;

                default:
                    //if call have Error, deserialize the error list and return
                    return serviceResponse.Content.ReadAsAsync<List<ErrorDetail>>().Result;
            }
        }



public List<ErrorDetail> GetDocumentUDF(int registrationDocumentId, int languageId, out List<DocumentUDF> documentUDF)
        {
            //Form the appropriate request uri for this call
            var requestUri = String.Format("{2}GetDocumentUDF?registrationDocumentId={0}&languageId={1}", registrationDocumentId, languageId, serviceUri);
            //Make the get call to web service layer
            HttpResponseMessage serviceResponse =
                Task<HttpResponseMessage>.Run(async () => { return await mdsClient.GetAsync(requestUri); }).Result;

            //Asses the status code and return
            switch (serviceResponse.StatusCode)
            {
                case HttpStatusCode.OK:
                    //The call was successful, deserialize the response to a Property Document list
                    documentUDF = serviceResponse.Content.ReadAsAsync<List<DocumentUDF>>().Result;
                    //No errors so return null
                    return null;

                default:
                    //if call have Error, deserialize the error list and return
                    documentUDF = null;
                    return serviceResponse.Content.ReadAsAsync<List<ErrorDetail>>().Result;
            }

        }



public List<ErrorDetail> GetDocumentUdfById(int registrationDocumentId, int udfId, int languageId, out DocumentUDF documentUdf)
        {
            //Form the appropriate request uri for this call
            var requestUri = String.Format("{3}GetDocumentUDFById?registrationDocumentId={0}&languageId={1}&udfId={2}", registrationDocumentId, languageId, udfId, serviceUri);
            //Make the get call to web service layer
            HttpResponseMessage serviceResponse =
                Task<HttpResponseMessage>.Run(async () => { return await mdsClient.GetAsync(requestUri); }).Result;

            //Asses the status code and return
            switch (serviceResponse.StatusCode)
            {
                case HttpStatusCode.OK:
                    //The call was successful, deserialize the response to a Property Document list
                    documentUdf = serviceResponse.Content.ReadAsAsync<DocumentUDF>().Result;
                    //No errors so return null
                    return null;

                default:
                    //if call have Error, deserialize the error list and return
                    documentUdf = null;
                    return serviceResponse.Content.ReadAsAsync<List<ErrorDetail>>().Result;
            }
        }


Monday 2 October 2017

Example of all the validation(Required,StringLength,Compare,Range,RegularExpression,Custom) in Webapi and Angular js

First write a view  model in Webapi

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace Implementwebapiinangularjs.Models
{
    public class EMPVM
    {


        [Required(ErrorMessage = "Eid should not be blank.")]
        public int? EID { get; set; }
        [Required(ErrorMessage = "Name should not be blank.")]
        public string NAME { get; set; }
        [Required(ErrorMessage = "Address should not be blank.")]
        public string ADDRESS { get; set; }
        [Required(ErrorMessage = "Password should not be blank.")]
        [StringLength(8, MinimumLength = 6, ErrorMessage = "Password length between 6 to 8.")]
        public string PASSWORD { get; set; }
        [Compare("PASSWORD", ErrorMessage = "Confirm password must be same as password.")]
        [Required(ErrorMessage = "Confimr password should not be blank.")]
        public string CP { get; set; }
        [Required(ErrorMessage = "Please select a gender.")]
        public string GENDER { get; set; }
        [Required(ErrorMessage = "Please select a hobby.")]
        public string HOBBY { get; set; }
        [Required(ErrorMessage = "Email should not be blank.")]
        [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Invalid email id.")]
        public string EMAIL { get; set; }
        [Required(ErrorMessage = "Dob should not be blank.")]
[Customvalidation(ErrorMessage="Dob should not greater than or equal to current date.")]
        public DateTime? DOB { get; set; }
        [Required(ErrorMessage = "SALARY should not be blank.")]
        [Range(5000, 500000, ErrorMessage = "Salary range between 5000 to 500000.")]
        public decimal? SALARY { get; set; }
        [Required(ErrorMessage = "Please select a country.")]
        public int? CID { get; set; }
        [Required(ErrorMessage = "Please select a state.")]
        public int? SID { get; set; }

    }
}

public class Customvalidation : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null)
            return false;
        else
            return !(DateTime.Now.Subtract(((DateTime)value)).Days <= 0);
    }
}


Web Api

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    [RoutePrefix("api/Empservice")]
    public class EmpserviceController : ApiController
    {
        [HttpGet]
        [Route("Allcountry")]
        public IHttpActionResult Allcountry()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.COUNTRies.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpGet]
        [Route("Allstate/{CID:int}")]
        public IHttpActionResult Allstate(int CID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.STATEs.Where(m=>m.CID==CID).ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpGet]
        [Route("Emps")]
        public IHttpActionResult Emps()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.EMPs.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpGet]
        [Route("Emp/{EID:int}",Name="Get")]
        public IHttpActionResult Emps(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.EMPs.Find(EID));
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpPost]
        [Route("Save")]
        public IHttpActionResult Save(EMPVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    if (ModelState.IsValid)
                    {
                        EMP emp = new EMP();
                        emp.EID = vm.EID??0;
                        emp.NAME = vm.NAME;
                        emp.ADDRESS = vm.ADDRESS;
                        emp.PASSWORD = vm.PASSWORD;
                        emp.GENDER = vm.GENDER;
                        emp.EMAIL = vm.EMAIL;
                        emp.SALARY = vm.SALARY;
                        emp.DOB = vm.DOB;
                        emp.CID = vm.CID;
                        emp.SID = vm.SID;
                        obj.EMPs.Add(emp);
                        obj.SaveChanges();
                        return Created(new Uri(Url.Link("Get",new{EID=vm.EID})),"Data Saved");
                    }
                    else
                        return BadRequest(ModelState);
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpPut]
        [Route("Update/{EID:int}")]
        public IHttpActionResult Update([FromUri]int EID,[FromBody]EMPVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    if (ModelState.IsValid)
                    {
                        EMP emp = obj.EMPs.Find(EID);
                        emp.NAME = vm.NAME;
                        emp.ADDRESS = vm.ADDRESS;
                        emp.PASSWORD = vm.PASSWORD;
                        emp.GENDER = vm.GENDER;
                        emp.EMAIL = vm.EMAIL;
                        emp.SALARY = vm.SALARY;
                        emp.DOB = vm.DOB;
                        emp.CID = vm.CID;
                        emp.SID = vm.SID;
                        obj.SaveChanges();
                        return Ok("Data Saved");
                    }
                    else
                        return BadRequest(ModelState);
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpDelete]
        [Route("Delete/{EID:int}")]
        public IHttpActionResult Delete(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    if (ModelState.IsValid)
                    {
                        EMP emp = obj.EMPs.Find(EID);
                        obj.EMPs.Remove(emp);
                        obj.SaveChanges();
                        return Ok("Data Deleted");
                    }
                    else
                        return BadRequest(ModelState);
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

    }
}


View in Angular Js


<!DOCTYPE html>
<html>
<head>
    <title></title>
<meta charset="utf-8" />
    <script src="angular.js"></script>
    <link href="bootstrap.css" rel="stylesheet" />
    <link href="bootstrap-theme.css" rel="stylesheet" />
    <script src="Scripts/angular-ui/ui-bootstrap.js"></script>
    <script src="Scripts/angular-ui/ui-bootstrap-tpls.js"></script>
</head>
<body ng-app="app" ng-controller="Ctrl">
    <div class="container" style="padding-top:10px">
        <div class="well">
            <form class="form-horizontal">
                <div class="form-group">
                    <label class="col-lg-4 control-label">EID</label>
                    <div class="col-lg-4">
                        <input type="text" class="form-control" ng-model="EMP.EID" />
                        <span style="color:red" ng-bind="errEid"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">NAME</label>
                    <div class="col-lg-4">
                        <input type="text" class="form-control" ng-model="EMP.NAME" />
                        <span style="color:red" ng-bind="errName"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">ADDRESS</label>
                    <div class="col-lg-4">
                        <textarea class="form-control" ng-model="EMP.ADDRESS" ></textarea>
                        <span style="color:red" ng-bind="errAdd"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">PASSWORD</label>
                    <div class="col-lg-4">
                        <input type="password" class="form-control" ng-model="EMP.PASSWORD" />
                        <span style="color:red" ng-bind="errPwd"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">CONFIRM PASSWORD</label>
                    <div class="col-lg-4">
                        <input type="password" class="form-control" ng-model="EMP.CP" />
                        <span style="color:red" ng-bind="errCpwd"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">GENDER</label>
                    <div class="col-lg-4">
                        <input type="radio"  ng-model="EMP.GENDER" value="Male" />Male
                        <input type="radio" ng-model="EMP.GENDER" value="Female" />Female
                        <span style="color:red" ng-bind="errSex"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">HOBBY</label>
                    <div class="col-lg-4">
                        <select class="form-control" ng-model="EMP.HOBBY"  >
                            <option value="">Select</option>
                            <option value="Cricket">Cricket</option>
                            <option value="Football">Football</option>
                            <option value="Baseball">Baseball</option>
                            <option value="Hockey">Hockey</option>
                        </select>
                        <span style="color:red" ng-bind="errHobby"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">EMAIL</label>
                    <div class="col-lg-4">
                        <input type="text" class="form-control" ng-model="EMP.EMAIL" />
                        <span style="color:red" ng-bind="errEmail"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">DOB</label>
                    <div class="col-lg-4">
                        <input type="text" class="form-control" ng-model="EMP.DOB" />
                        <span style="color:red" ng-bind="errDob"></span>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-lg-4 control-label">SALARY</label>
                    <div class="col-lg-4">
                        <input type="text" class="form-control" ng-model="EMP.SALARY" />
                        <span style="color:red" ng-bind="errSalary"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">COUNTRY</label>
                    <div class="col-lg-4">
                        <select class="form-control" ng-model="EMP.CID" ng-options="c.CID as c.CNAME for c in listc" ng-change="fillddl()" >
                            <option value="">Select</option>
                        </select>
                        <span style="color:red" ng-bind="errCid"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">STATE</label>
                    <div class="col-lg-4">
                        <select class="form-control" ng-model="EMP.SID" ng-options="c.SID as c.SNAME for c in lists">
                            <option value="">Select</option>
                        </select>
                        <span style="color:red" ng-bind="errSid"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label"></label>
                    <div class="col-lg-4">
                        <input type="button" value="Save" style="width:80px" class="btn btn-primary" ng-click="save()" />
                        <input type="button" value="Update" style="width:80px" class="btn btn-primary" ng-click="update()" />
                        <input type="button" value="Reset" style="width:80px" class="btn btn-primary" ng-click="reset()" />
                    </div>
                </div>

            </form>
        </div>
        <div class="well">
            <div class="form-group">
                <label class="col-lg-1 control-label">SEARCH</label>
                <div class="col-lg-3">
                    <input type="text" placeholder="Search" uib-typeahead="c for c in listName| filter:$viewValue | limitTo:8" ng-model="search.NAME" class="form-control" />
              
                </div>
            </div>

            <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
                <thead class="bg-primary">
                    <tr>
                        <th>EID</th>
                        <th>NAME</th>
                        <th>GENDER</th>
                        <th>DOB</th>
                        <th>SALARY</th>
                        <th>(RS)SALARY</th>
                        <th>ACTION</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="c in liste|filter:search">
                        <td>{{c.EID|Eidfilter}}</td>
                        <td>{{c.NAME|uppercase}}</td>
                        <td>{{c.GENDER|lowercase}}</td>
                        <td>{{c.DOB|date:"dd-MMM-yyyy"}}</td>
                        <td>{{c.SALARY|number:2}}</td>
                        <td>{{c.SALARY|currency:'Rs. '}}</td>
                        <td>
                            <a ng-click="edit(c.EID)">Edit</a>|
                            <a ng-click="del(c.EID)">Delete</a>
                        </td>

                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>
<script type="text/javascript">
    angular.module("app", ['ui.bootstrap'])
    .controller("Ctrl", function ($scope, factoryEmp) {
        function CLR()
        {
            $scope.EMP = new emp();
            $scope.listName = [];
        } CLR();
        $scope.save = function ()
        {
            factoryEmp.Save($scope.EMP).error(function (ajXHR) {
                if (ajXHR.ModelState["eMPVM.EID"] != "")
                    $scope.errEid = ajXHR.ModelState["eMPVM.EID"];
                else
                    $scope.errEid = "";
                if (ajXHR.ModelState["eMPVM.NAME"] != "")
                    $scope.errName = ajXHR.ModelState["eMPVM.NAME"];
                else
                    $scope.errName = "";
                if (ajXHR.ModelState["eMPVM.ADDRESS"] != "")
                    $scope.errAdd = ajXHR.ModelState["eMPVM.ADDRESS"];
                else
                    $scope.errAdd = "";
                if (ajXHR.ModelState["eMPVM.PASSWORD"] != "")
                    $scope.errPwd = ajXHR.ModelState["eMPVM.PASSWORD"];
                else
                    $scope.errPwd = "";
                if (ajXHR.ModelState["eMPVM.CP"] != "")
                    $scope.errCpwd = ajXHR.ModelState["eMPVM.CP"];
                else
                    $scope.errCpwd = "";
                if (ajXHR.ModelState["eMPVM.GENDER"] != "")
                    $scope.errSex = ajXHR.ModelState["eMPVM.GENDER"];
                else
                    $scope.errSex = "";
                if (ajXHR.ModelState["eMPVM.HOBBY"] != "")
                    $scope.errHobby = ajXHR.ModelState["eMPVM.HOBBY"];
                else
                    $scope.errHobby = "";
                if (ajXHR.ModelState["eMPVM.EMAIL"] != "")
                    $scope.errEmail = ajXHR.ModelState["eMPVM.EMAIL"];
                else
                    $scope.errEmail = "";
                if (ajXHR.ModelState["eMPVM.DOB"] != "")
                    $scope.errDob = ajXHR.ModelState["eMPVM.DOB"];
                else
                    $scope.errDob = "";
                if (ajXHR.ModelState["eMPVM.SALARY"] != "")
                    $scope.errSalary = ajXHR.ModelState["eMPVM.SALARY"];
                else
                    $scope.errSalary = "";
                if (ajXHR.ModelState["eMPVM.CID"] != "")
                    $scope.errCid = ajXHR.ModelState["eMPVM.CID"];
                else
                    $scope.errCid = "";
                if (ajXHR.ModelState["eMPVM.SID"] != "")
                    $scope.errSid = ajXHR.ModelState["eMPVM.SID"];
                else
                    $scope.errSid = "";



                







            }).then(function (promise) {
                alert(promise.data);
                CLR();
                fill();
            });
        }
        factoryEmp.Getc().then(function (promise) {
            $scope.listc = promise.data;
        });
        function fx(s)
        {
            factoryEmp.Gets(s).then(function (promise) {
                $scope.lists = promise.data;
            });
        }
        $scope.fillddl = function ()
        {
            fx($scope.EMP.CID);
        }
        function fill()
        {
            factoryEmp.Gete().error(function (ajXHR) {
                alert(ajXHR.responseText);
            }).then(function (promise) {
                
                $scope.liste = promise.data;
                for (var i = 0; i < promise.data.length; i++)
                {
                    $scope.listName.push(promise.data[i].NAME);
                }
                
            });
        } fill();
        $scope.edit = function (s)
        {
            factoryEmp.Get(s).then(function (promise) {
                $scope.EMP = promise.data;
                fx($scope.EMP.CID);
                $scope.EMP.CP = $scope.EMP.PASSWORD;
                var dt=new Date($scope.EMP.DOB);
                $scope.EMP.DOB = (dt.getMonth() < 10 ? "0" + dt.getMonth() : dt.getMonth()) + "-" + (dt.getDate() < 10 ? "0" + dt.getDate() : dt.getDate()) + "-" + dt.getFullYear();
            });
        }
        $scope.reset = function ()
        {
            CLR();
        }
        $scope.update = function () {
            factoryEmp.Update($scope.EMP).error(function (ajXHR) {
                if (ajXHR.ModelState["eMPVM.EID"] != "")
                    $scope.errEid = ajXHR.ModelState["eMPVM.EID"];
                else
                    $scope.errEid = "";
                if (ajXHR.ModelState["eMPVM.NAME"] != "")
                    $scope.errName = ajXHR.ModelState["eMPVM.NAME"];
                else
                    $scope.errName = "";
                if (ajXHR.ModelState["eMPVM.ADDRESS"] != "")
                    $scope.errAdd = ajXHR.ModelState["eMPVM.ADDRESS"];
                else
                    $scope.errAdd = "";
                if (ajXHR.ModelState["eMPVM.PASSWORD"] != "")
                    $scope.errPwd = ajXHR.ModelState["eMPVM.PASSWORD"];
                else
                    $scope.errPwd = "";
                if (ajXHR.ModelState["eMPVM.CP"] != "")
                    $scope.errCpwd = ajXHR.ModelState["eMPVM.CP"];
                else
                    $scope.errCpwd = "";
                if (ajXHR.ModelState["eMPVM.GENDER"] != "")
                    $scope.errSex = ajXHR.ModelState["eMPVM.GENDER"];
                else
                    $scope.errSex = "";
                if (ajXHR.ModelState["eMPVM.HOBBY"] != "")
                    $scope.errHobby = ajXHR.ModelState["eMPVM.HOBBY"];
                else
                    $scope.errHobby = "";
                if (ajXHR.ModelState["eMPVM.EMAIL"] != "")
                    $scope.errEmail = ajXHR.ModelState["eMPVM.EMAIL"];
                else
                    $scope.errEmail = "";
                if (ajXHR.ModelState["eMPVM.DOB"] != "")
                    $scope.errDob = ajXHR.ModelState["eMPVM.DOB"];
                else
                    $scope.errDob = "";
                if (ajXHR.ModelState["eMPVM.SALARY"] != "")
                    $scope.errSalary = ajXHR.ModelState["eMPVM.SALARY"];
                else
                    $scope.errSalary = "";
                if (ajXHR.ModelState["eMPVM.CID"] != "")
                    $scope.errCid = ajXHR.ModelState["eMPVM.CID"];
                else
                    $scope.errCid = "";
                if (ajXHR.ModelState["eMPVM.SID"] != "")
                    $scope.errSid = ajXHR.ModelState["eMPVM.SID"];
                else
                    $scope.errSid = ""


            }).then(function (promise) {
                alert(promise.data);
                CLR();
                fill();
            });
        }
        $scope.del = function (s)
        {
            if (confirm('Do you want to delete it?'))
            {
                factoryEmp.Delete(s).then(function (promise) {
                    alert(promise.data);
                    fill();

                });

            }
        }
    })
        .filter("Eidfilter", function () {
            return function (x) {
                if (x == 1)
                    return "Siv1";
                else if (x == 2)
                    return "Sankar1";
                else
                    return "Mahadev1";
            }
        })
    .factory("factoryEmp", function ($http) {
        var fac = {};
        fac.Getc = function ()
        {
            return $http.get("http://localhost:5763/api/Empservies/AllCountry");
        }
        fac.Gets = function (CID) {
            return $http.get("http://localhost:5763/api/Empservies/AllState/"+CID);
        }
        fac.Save = function (EMP) {
            return $http.post("http://localhost:5763/api/Empservies/Save",EMP);
        }
        fac.Gete = function () {
            return $http.get("http://localhost:5763/api/Empservies/AllEmps");
        }
        fac.Get = function (EID) {
            return $http.get("http://localhost:5763/api/Empservies/AllEmp/"+EID);
        }
        fac.Update = function (EMP) {
            return $http.put("http://localhost:5763/api/Empservies/Update/"+EMP.EID, EMP);
        }
        fac.Delete = function (EID)
        {
            return $http.delete("http://localhost:5763/api/Empservies/Delete/" + EID);
        }


        return fac;
    });
    function emp()
    {
        return {
            EID: null,
            NAME: null,
            ADDRESS: null,
            PASSWORD: null,
            GENDER: null,
            HOBBY: null,
            EMAIL: null,
            DOB: null,
            SALARY: null,
            CID: null,
            SID:null
        }
    }
</script>

Friday 29 September 2017

Example of all the validation(Required,StringLength,Compare,Range,RegularExpression,Remote,Custom) in MVC

View Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Web.Mvc;

namespace MvcApplication2.Models
{
    public class EMPVM
    {
        [Required(ErrorMessage = "Eid should not be blank.")]
        public int? EID { get; set; }
        [Required(ErrorMessage = "Name should not be blank.")]
        public string NAME { get; set; }
        [Required(ErrorMessage = "Password should not be blank.")]
        [StringLength(8,MinimumLength=6,ErrorMessage="Password length between 6 to 8 charecters.")]
        [DataType(DataType.Password)]
        public string PASSWORD { get; set; }
        [DisplayName("CONFIRM PASSWORD")]
        [System.ComponentModel.DataAnnotations.Compare("PASSWORD",ErrorMessage="Confirm password must be same with passwrod.")]
        [Required(ErrorMessage = "Confirm password should not be blank.")]
        [DataType(DataType.Password)]
        public string CP { get; set; }
        [Required(ErrorMessage="Address should not be blank.")]
        [DataType(DataType.MultilineText)]
        public string ADDRESS { get; set; }
        [Required(ErrorMessage = "Salary should not be blank.")]
        [Range(5000,500000,ErrorMessage="Salary range between 5000 to 500000.")]
        public decimal? SALARY { get; set; }
        [Required(ErrorMessage = "Dob should not be blank.")]
        [Remote("Check","Home",ErrorMessage="Dob should not greater than or equal to current date.")]
        public DateTime? DOB { get; set; }
        [Required(ErrorMessage = "Email should not be blank.")]
        [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",ErrorMessage="Invalid email Id.")]
        public string EMAIL { get; set; }
        [Required(ErrorMessage = "Gender should not be blank.")]
        public string GENDER { get; set; }
        [Hvalidate(ErrorMessage = "Please select a hobby.")]
        [DisplayName("HOBBY")]
        public List<MetaData> LHOBBY { get; set; }
        [Ivalidate(ErrorMessage = "Please select a interest.")]
        public List<string> INTEREST { get; set; }
        public List<MetaData> LINTEREST{ get; set;}
        [Required(ErrorMessage = "Please select a country.")]
        public int COUNTRY { get; set; }
        public List<MetaData> LCOUNTRY { get; set; }
        [Required(ErrorMessage = "Please select a state.")]
        public int STATE { get; set; }
        public List<MetaData> LSTATE { get; set; }
        public EMPVM()
        {
            LHOBBY = new List<MetaData>();
            LINTEREST = new List<MetaData>();
            LCOUNTRY = new List<MetaData>();
            LSTATE = new List<MetaData>();
        }



    }
    public class Hvalidate : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (value == null)
                return false;
         return ((List<MetaData>)value).Count(m=>m.Selected==true)>0;
        }
    }
    public class Ivalidate:ValidationAttribute
    {
         public override bool IsValid(object value)
         {
             if (value == null)
                 return false;
             return !(((List<string>)value).ToList().Count() == 0);
         }
    }
    public class MetaData
    {
        public int ID { get; set; }
        public string NAME { get; set; }
        public bool Selected { get; set; }
    }
    public class MetaData1
    {
   
        public string NAME { get; set; }
     
    }
}

Controller


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;

namespace MvcApplication2.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        [HttpGet]
        public ActionResult Index()
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return View(obj.EMPs.ToList());
            }
        }
        [HttpGet]
        public ActionResult Create()
        {
            using (Database1Entities obj = new Database1Entities())
            {
                EMPVM vm = new EMPVM();
                vm.LCOUNTRY = obj.COUNTRies.Select(m => new MetaData { ID = m.CID, NAME = m.CNAME }).ToList();
                vm.LHOBBY = obj.HOBBies.Select(m => new MetaData { ID = m.HID, NAME = m.HNAME }).ToList();
                vm.LINTEREST = obj.INTRESTs.Select(m => new MetaData { ID = m.IID, NAME = m.INAME }).ToList();
                vm.LSTATE = new List<MetaData>();
                return View(vm);
            }

        }
        [HttpPost]
        public ActionResult Create(EMPVM vm)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                if (ModelState.IsValid)
                {
                    EMP emp = new EMP();
                    emp.EID = vm.EID ?? 0;
                    emp.NAME = vm.NAME;
                    emp.PASSWORD = vm.PASSWORD;
                    emp.ADDRESS = vm.ADDRESS;
                    emp.SALARY = vm.SALARY;
                    emp.DOB = vm.DOB;
                    emp.EMAIL = vm.EMAIL;
                    emp.GENDER = vm.GENDER;
                    emp.CID = vm.COUNTRY;
                    emp.SID = vm.STATE;
                    obj.EMPs.Add(emp);
                    obj.SaveChanges();
                    foreach (MetaData md in vm.LHOBBY)
                    {
                        if (md.Selected)
                        {
                            HOBBYMAP hm = new HOBBYMAP();
                            hm.EID = vm.EID;
                            hm.HID = md.ID;
                            obj.HOBBYMAPs.Add(hm);
                            obj.SaveChanges();
                        }
                    }
                    foreach (string s in vm.INTEREST)
                    {
                        INTERESTMAP im = new INTERESTMAP();
                        im.EID = vm.EID;
                        im.IID = Convert.ToInt32(s);
                        obj.INTERESTMAPs.Add(im);
                        obj.SaveChanges();
                    }
                    return RedirectToAction("Index");
                }
                else
                {
                    vm.LCOUNTRY = obj.COUNTRies.Select(m => new MetaData { ID = m.CID, NAME = m.CNAME }).ToList();
                    vm.LHOBBY = obj.HOBBies.Select(m => new MetaData { ID = m.HID, NAME = m.HNAME }).ToList();
                    vm.LINTEREST = obj.INTRESTs.Select(m => new MetaData { ID = m.IID, NAME = m.INAME }).ToList();
                    vm.LSTATE = obj.STATEs.Where(m => m.CID == vm.COUNTRY).Select(m => new MetaData { ID = m.SID, NAME = m.SNAME }).ToList();
                    return View(vm);
                }
            }
        }
        [HttpGet]
        public ActionResult Edit(int id)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                EMPVM vm = new EMPVM();
                vm.LCOUNTRY = obj.COUNTRies.Select(m => new MetaData { ID = m.CID, NAME = m.CNAME }).ToList();
                vm.LHOBBY = obj.HOBBies.Select(m => new MetaData { ID = m.HID, NAME = m.HNAME }).ToList();
                vm.LINTEREST = obj.INTRESTs.Select(m => new MetaData { ID = m.IID, NAME = m.INAME }).ToList();
                EMP emp=obj.EMPs.Find(id);
                vm.LSTATE = obj.STATEs.Where(m => m.CID == emp.CID).Select(n => new MetaData { ID=n.SID,NAME=n.SNAME }).ToList();
                vm.EID = emp.EID;
                vm.NAME = emp.NAME;
                vm.PASSWORD = emp.PASSWORD;
                vm.CP = emp.PASSWORD;
                vm.ADDRESS = emp.ADDRESS;
                vm.SALARY = emp.SALARY;
                vm.DOB = emp.DOB;
                vm.EMAIL = emp.EMAIL;
                vm.GENDER = emp.GENDER.Trim();
                vm.COUNTRY = emp.CID??0;
                vm.STATE = emp.SID??0;
                List<int> lst = obj.HOBBYMAPs.Where(m => m.EID == id).Select(n =>n.HID.Value).ToList();
                List<MetaData> hmd = obj.HOBBies.Where(n => lst.Contains(n.HID)).Select(m => new MetaData { ID=m.HID,NAME=m.HNAME,Selected=true }).ToList();
                List<MetaData> hmd2 = obj.HOBBies.Where(n => lst.Contains(n.HID) == false).Select(m => new MetaData { ID = m.HID, NAME = m.HNAME, Selected = false }).ToList();
                vm.LHOBBY = hmd.Union(hmd2).ToList();
                List<string> ls=new List<string>();
                foreach(int  i in obj.INTERESTMAPs.Where(m=>m.EID==id).Select(n=>n.IID))
                {
                    ls.Add(i.ToString());
                }
                vm.INTEREST = ls;
                return View(vm);

            }
      }
        [HttpPost]
        public ActionResult Edit(EMPVM vm)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                if (ModelState.IsValid)
                {
                    EMP emp =obj.EMPs.Find(vm.EID);
                    emp.EID = vm.EID ?? 0;
                    emp.NAME = vm.NAME;
                    emp.PASSWORD = vm.PASSWORD;
                    emp.ADDRESS = vm.ADDRESS;
                    emp.SALARY = vm.SALARY;
                    emp.DOB = vm.DOB;
                    emp.EMAIL = vm.EMAIL;
                    emp.GENDER = vm.GENDER;
                    emp.CID = vm.COUNTRY;
                    emp.SID = vm.STATE;
                    obj.SaveChanges();
                    List<HOBBYMAP> lm=obj.HOBBYMAPs.Where(m => m.EID == vm.EID).ToList();
                    foreach (HOBBYMAP hm in lm)
                    {
                        obj.HOBBYMAPs.Remove(hm);
                        obj.SaveChanges();
                    }
                    foreach (MetaData md in vm.LHOBBY)
                    {
                        if (md.Selected)
                        {
                            HOBBYMAP hm = new HOBBYMAP();
                            hm.EID = vm.EID;
                            hm.HID = md.ID;
                            obj.HOBBYMAPs.Add(hm);
                            obj.SaveChanges();
                        }
                    }
                   List<INTERESTMAP> lm1=obj.INTERESTMAPs.Where(m => m.EID == vm.EID).ToList();
                    foreach (INTERESTMAP im in lm1)
                    {
                        obj.INTERESTMAPs.Remove(im);
                        obj.SaveChanges();
                    }
                    foreach (string s in vm.INTEREST)
                    {
                        INTERESTMAP im = new INTERESTMAP();
                        im.EID = vm.EID;
                        im.IID = Convert.ToInt32(s);
                        obj.INTERESTMAPs.Add(im);
                        obj.SaveChanges();
                    }
                    return RedirectToAction("Index");
                }
                else
                {
                    vm.LCOUNTRY = obj.COUNTRies.Select(m => new MetaData { ID = m.CID, NAME = m.CNAME }).ToList();
                    vm.LHOBBY = obj.HOBBies.Select(m => new MetaData { ID = m.HID, NAME = m.HNAME }).ToList();
                    vm.LINTEREST = obj.INTRESTs.Select(m => new MetaData { ID = m.IID, NAME = m.INAME }).ToList();
                    vm.LSTATE = obj.STATEs.Where(m => m.CID == vm.COUNTRY).Select(m => new MetaData { ID = m.SID, NAME = m.SNAME }).ToList();
                    return View(vm);
                }
            }
        }
        public ActionResult Delete(int id)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                EMP vm = obj.EMPs.Find(id);
                obj.EMPs.Remove(vm);
                obj.SaveChanges();
                List<HOBBYMAP> lm = obj.HOBBYMAPs.Where(m => m.EID == vm.EID).ToList();
                foreach (HOBBYMAP hm in lm)
                {
                    obj.HOBBYMAPs.Remove(hm);
                    obj.SaveChanges();
                }
                List<INTERESTMAP> lm1 = obj.INTERESTMAPs.Where(m => m.EID == vm.EID).ToList();
                foreach (INTERESTMAP im in lm1)
                {
                    obj.INTERESTMAPs.Remove(im);
                    obj.SaveChanges();
                }
                return RedirectToAction("Index");

            }
        }
     

        public JsonResult Check(DateTime? DOB)
        {
         
            DateTime dt = DateTime.Now;
            int dif = dt.Subtract(DOB.Value).Days;
            return Json(!(dif <= 0), JsonRequestBehavior.AllowGet);

            //if(DOB!=null)
            //{
            //    DateTime dt = DateTime.Now;
            //    int dif = dt.Subtract(DOB.Value).Days;
            //    return Json(!(dif <= 0), JsonRequestBehavior.AllowGet);
            //}
            // else
            //     return Json(null, JsonRequestBehavior.AllowGet);

        }
        public JsonResult Fillddl(int ID)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return Json(obj.STATEs.Where(m => m.CID == ID).Select(n => new MetaData { ID = n.SID, NAME = n.SNAME }).ToList(), JsonRequestBehavior.AllowGet);
            }

        }
       
    }
}


View

@model MvcApplication2.Models.EMPVM

@{
    ViewBag.Title = "Create";
}



@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>EMPVM</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.EID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EID)
            @Html.ValidationMessageFor(model => model.EID)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.NAME)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.NAME)
            @Html.ValidationMessageFor(model => model.NAME)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.PASSWORD)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PASSWORD)
            @Html.ValidationMessageFor(model => model.PASSWORD)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.CP)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CP)
            @Html.ValidationMessageFor(model => model.CP)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ADDRESS)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ADDRESS)
            @Html.ValidationMessageFor(model => model.ADDRESS)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.SALARY)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.SALARY)
            @Html.ValidationMessageFor(model => model.SALARY)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.DOB)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DOB)
            @Html.ValidationMessageFor(model => model.DOB)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.EMAIL)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EMAIL)
            @Html.ValidationMessageFor(model => model.EMAIL)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.GENDER)
        </div>
        <div class="editor-field">
            @Html.RadioButtonFor(model => model.GENDER,"Male")Male
            @Html.RadioButtonFor(model => model.GENDER, "Female")Female
            @Html.ValidationMessageFor(model => model.GENDER)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.LHOBBY)
        </div>
        <div class="editor-field">
            @{
    for (int i = 0; i < Model.LHOBBY.Count; i++)
    {
        @Html.HiddenFor(m=>m.LHOBBY[i].ID)
        @Html.HiddenFor(m=>m.LHOBBY[i].NAME) 
        @Html.CheckBoxFor(m=>m.LHOBBY[i].Selected)
        @Html.DisplayFor(m=>m.LHOBBY[i].NAME)<br />
    }    
            }
            @Html.ValidationMessageFor(model => model.LHOBBY)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.INTEREST)
        </div>
        <div class="editor-field">
            @Html.ListBoxFor(model =>model.INTEREST,new SelectList(Model.LINTEREST,"ID","NAME"))
            @Html.ValidationMessageFor(model => model.INTEREST)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.COUNTRY)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.COUNTRY, new SelectList(Model.LCOUNTRY, "ID", "NAME"), "Select", new { @id="ddl"})
            @Html.ValidationMessageFor(model => model.COUNTRY)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.STATE)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.STATE, new SelectList(Model.LSTATE, "ID", "NAME"), "Select", new { @id="ddl1"})
            @Html.ValidationMessageFor(model => model.STATE)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script type="text/javascript">
    $(function () {
        $('#ddl').change(function () {
            $.ajax({
                url: '/Home/Fillddl',
                data: { ID: $('#ddl').val() },
                type: 'Get',
                success: function (data) {
                    $('#ddl1').empty();
                    $('#ddl1').append("<option value='0'>Select</option>");
                    $.each(data, function (i, j) {
                        $('#ddl1').append("<option value='"+j.ID+"'>"+j.NAME+"</option>");
                    });
                }
            });
        });
    });
</script>