Thursday, 31 October 2013

How to Generate Models using entity frmework

Entity framwork

RightClick on Models Folder 
-> Add new item 
-> Data 
->ADO.NET Entity Data Model
-> name the model 
-> Generate From db 
-> edmx file will be generated 
-> rightclick on open area of .edmx file 
-> Add Code Generation Item 
-> Select Online template and serach for ADO.NET DBContext 
-> using that Entity object generator create the model 
-> it will create model class for each and every table
   of your database.

Edit View

@model MVCDemo.Models.EmployeeMaster
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
    Edit</h2>
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.20.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<link href="../../Scripts/Datepicker/jquery-ui.css" rel="stylesheet" type="text/css" />
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/Datepicker")
<script language="javascript" type="text/javascript">
    var createuser = jQuery.noConflict();
    createuser(function () {
        createuser("#CountryId").change(function () {
            var selectedItem = createuser(this).val();
            var ddlCities = createuser("#CityId");
            if (selectedItem.toString().length > 0 && parseInt(selectedItem) > 0) {
                createuser.ajax({
                    cache: false,
                    type: "GET",
                    url: '@Url.Action("GetCity", "Employee")',
                    async: false,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: { "CountryId": selectedItem },
                    success: function (data) {
                        ddlCities.html('');
                        createuser.each(data, function (id, option) {
                            ddlCities.append(createuser('<option></option>').val(option.Value).html(option.Text));
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert('Failed to retrieve City.');
                    }
                });
            }
            else {
                ddlCities.html('');
                ddlCities.append(createuser('<option></option>').val('').html('--Select City--'));
            }
        });
    });

    var createuser = jQuery.noConflict();
    createuser(document).ready(function () {
        var selectedItem = createuser("#CountryId").val();
        var ddlCities = createuser("#CityId");
        if (selectedItem.toString().length > 0 && parseInt(selectedItem) > 0) {
            createuser.ajax({
                cache: false,
                type: "GET",
                url: '@Url.Action("GetCity", "Employee")',
                async: false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: { "CountryId": selectedItem },
                success: function (data) {
                    ddlCities.html('');
                    createuser.each(data, function (id, option) {
                        ddlCities.append(createuser('<option></option>').val(option.Value).html(option.Text));
                    });
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Failed to retrieve City.');
                }
            });
            createuser("#CityId").val('@ViewBag.CityId');
            createuser("#Occupation").val('@ViewBag.Occu');
        }
        else {
            ddlCities.html('');
            ddlCities.append(createuser('<option></option>').val('').html('--Select City--'));
        }
    });

    var jqdatepicker = jQuery.noConflict();

    jqdatepicker(function () {
        jqdatepicker("#DOB").datepicker
            ({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'mm/dd/yy'
            });

    });

    var createuser1 = jQuery.noConflict();
    createuser1(function () {
        $('#DOB').blur(function () {
            var birthday = createuser1(this).val();
            if (birthday.value != '') {
                var birthdayDate = new Date(birthday);
                dateNow = new Date();

                var years = dateNow.getFullYear() - birthdayDate.getFullYear();
                var months = dateNow.getMonth() - birthdayDate.getMonth();
                var days = dateNow.getDate() - birthdayDate.getDate();
                alert(days);
                if (isNaN(years)) {

                    document.getElementById('Age').value = '';
                    document.getElementById('lblError').innerHTML = 'Input date is incorrect!';
                    return false;

                }
                else {
                    document.getElementById('lblError').innerHTML = '';

                    if (months < 0 || (months == 0 && days < 0)) {

                        //alert(document.getElementById('Age'));
                        years = parseInt(years) - 1;
                        document.getElementById('Age').value = years + ' Years ' + months + ' Month ' + days + ' days'
                    }
                    else {
                        //alert(document.getElementById('Age').value);
                        document.getElementById('Age').value = years + ' Years ' + months + ' Month ' + days + ' days'
                    }
                }
            }
        });
    });

    var createuser = jQuery.noConflict();
    createuser(function () {
        createuser("#Occupation").change(function () {
            var selectedItem = createuser(this).val();
            var div1 = document.getElementById('GrossSalary');
            if (selectedItem.toString() == "Job" || selectedItem.toString() == "Bussiness") {
                div1.style.display = "block";
            }
            else {
                div1.style.display = "none";
            }
        });
    });

    var createuser = jQuery.noConflict();
    createuser(document).ready(function () {
        var selectedItem = createuser("#Occupation").val();
        var div1 = document.getElementById('GrossSalary');
        if (selectedItem.toString() == "Job" || selectedItem.toString() == "Bussiness") {
            div1.style.display = "block";
        }
        else {
            div1.style.display = "none";
        }
    });

</script>
@using (Html.BeginForm("Edit", "Employee", FormMethod.Post, new { id = "EditEmp" }))
{
    @Html.HiddenFor(model => model.EmployeeId)
    <div>
        <div>
            <div>
                Employee Code:
            </div>
            <div>
                @Html.TextBoxFor(ModelItem => Model.EmpCode)
            </div>
            <div>
                Emp Name:
            </div>
            <div>
                @Html.TextBoxFor(ModelItem => Model.EmpName)
            </div>
            <div>
                Gender:
            </div>
            <div>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@Html.RadioButtonFor(model => model.Gender, "Male", new { id = "male", @style = "width:0px;" })Male
                @*@Html.Label("male", "Male")*@
            </div>
            <div>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@Html.RadioButtonFor(model => model.Gender, "Female", new { id = "female", @style = "width:0px;" })Female
                @* @Html.Label("female", "Female")*@
            </div>
            <div>
                Country:
            </div>
            <div>
                @Html.DropDownList("CountryId", ViewBag.Country as SelectList, "--Select City--")
            </div>
            <div>
                City:
            </div>
            <div>
                @* @Html.DropDownListFor(ModelItem => Model.CityMaster.CityId, new SelectList(ViewBag.City, "CityId", "CityName", ViewBag.SelCity), new { style = "width:310px" })
                @Html.ValidationMessageFor(ModelItem => Model.CityMaster.CityId)*@
                <select id="CityId" name="CityId" style="max-width: 250px;">
                    <option value="">--Select City--</option>
                </select>
                @*<select id="CityId">
                    <option>--Select City--</option>
                </select>*@
            </div>
            <div>
                DOB
            </div>
            <div>
                @Html.EditorFor(ModelItem => Model.DOB)
                @* <input type="text" id="DOB" name="DOB" value='@ViewBag.DOB' onblur="getAge(this)" />*@
                <div id="lblError">
                </div>
            </div>
            <div>
                Age
            </div>
            <div>
                @*<div id="Age"></div>*@
                @Html.TextBoxFor(ModelItem => Model.Age, new { id = "Age" })
                @*<input type="text" id="Age" name="AgeMonth" />*@
            </div>
            <div>
                Occupation
            </div>
            <div>
                @*@Html.DropDownList("CountryId", ViewBag.Country as SelectList, "--Select City--")*@
                @Html.DropDownList("Occupation", ViewBag.Occupation as SelectList)
            </div>
            <div id="GrossSalary">
                <div>
                    GrossSalary
                </div>
                <div>
                    @Html.TextBoxFor(ModelItem => Model.GrossSalary)
                </div>
            </div>
            <div>
                <input type="submit" value="submit" />
                <a href="/Employee/ListEmployees" style = "text-decoration:none;">
                    <input type="button" value="Cancel" >
                </a>
                @*<input type="button" onclick="document.location.href('Employee/ListEmployees')" value="Cancel" />*@
            </div>
        </div>
    </div>
}

Add View

@model MVCDemo.Models.EmployeeMaster
@{
    ViewBag.Title = "Add";
    Layout = "~/Views/Shared/_Layout.cshtml";
  
}
<h2>
    Add</h2>
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.20.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<link href="../../Scripts/Datepicker/jquery-ui.css" rel="stylesheet" type="text/css" />
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/Datepicker")
<script language="javascript" type="text/javascript">
    var createuser = jQuery.noConflict();
    createuser(function () {
        createuser("#CountryId").change(function () {
            var selectedItem = createuser(this).val();
            var ddlCities = createuser("#CityId");
            if (selectedItem.toString().length > 0 && parseInt(selectedItem) > 0) {
                createuser.ajax({
                    cache: false,
                    type: "GET",
                    url: '@Url.Action("GetCity", "Employee")',
                    async: false,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: { "CountryId": selectedItem },
                    success: function (data) {
                        ddlCities.html('');
                        createuser.each(data, function (id, option) {
                            ddlCities.append(createuser('<option></option>').val(option.Value).html(option.Text));
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert('Failed to retrieve City.');
                    }
                });
            }
            else {
                ddlCities.html('');
                ddlCities.append(createuser('<option></option>').val('').html('--Select City--'));
            }
        });
    });

    var jqdatepicker = jQuery.noConflict();

    jqdatepicker(function () {
        jqdatepicker("#DOB").datepicker
            ({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'mm/dd/yy'
            });

    });
        var createuser1 = jQuery.noConflict();
        createuser1(function () {
            $('#DOB').blur(function () {
                var birthday = createuser1(this).val();
                if (birthday.value != '') {
                    var birthdayDate = new Date(birthday);
                    dateNow = new Date();

                    var years = dateNow.getFullYear() - birthdayDate.getFullYear();
                    var months = dateNow.getMonth() - birthdayDate.getMonth();
                    var days = dateNow.getDate() - birthdayDate.getDate();
                    if (isNaN(years)) {

                        document.getElementById('Age').value = '';
                        document.getElementById('lblError').innerHTML = 'Input date is incorrect!';
                        return false;

                    }
                    else {
                        document.getElementById('lblError').innerHTML = '';

                        if (months < 0 || (months == 0 && days < 0)) {

                            //alert(document.getElementById('Age'));
                            years = parseInt(years) - 1;
                            document.getElementById('Age').value = years + ' Years ' + months + ' Month'
                        }
                        else {
                            //alert(document.getElementById('Age').value);
                            document.getElementById('Age').value = years + ' Years ' + months + ' Month'
                        }
                    }
                }
            });
        });

    var createuser = jQuery.noConflict();
    createuser(function () {
        createuser("#Occupation").change(function () {
            var selectedItem = createuser(this).val();
            var div1 = document.getElementById('GrossSalary');
            if (selectedItem.toString() == "Job" || selectedItem.toString() == "Bussiness") {
                div1.style.display = "block";
            }
            else {
                div1.style.display = "none";
            }
        });
    });
</script>
@using (Html.BeginForm("Add", "Employee", FormMethod.Post, new { id = "AddEmp" }))
{
    <div>
        <div>
            <div>
                Employee Code:
            </div>
            <div>
                @Html.TextBoxFor(ModelItem => Model.EmpCode)
            </div>
            <div>
                Emp Name:
            </div>
            <div>
                @Html.TextBoxFor(ModelItem => Model.EmpName)
            </div>
            <div>
                Gender:
            </div>
            <div>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@Html.RadioButtonFor(model => model.Gender, "Male", new { id = "male", @style = "width:0px;" })Male
                @*@Html.Label("male", "Male")*@
            </div>
            <div>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@Html.RadioButtonFor(model => model.Gender, "Female", new { id = "female", @style = "width:0px;" })Female
                @* @Html.Label("female", "Female")*@
            </div>
            <div>
                Country:
            </div>
            <div>
                @Html.DropDownList("CountryId", ViewBag.Country as SelectList, "--Select Country--")
            </div>
            <div>
                City:
            </div>
            <div>
                @* @Html.DropDownListFor(ModelItem => Model.CityMaster.CityId, new SelectList(ViewBag.City, "CityId", "CityName", ViewBag.SelCity), new { style = "width:310px" })
                @Html.ValidationMessageFor(ModelItem => Model.CityMaster.CityId)*@
                <select id="CityId" name="CityId" style="max-width: 250px;">
                    <option value="">--Select City--</option>
                </select>
                @*<select id="CityId">
                    <option>--Select City--</option>
                </select>*@
            </div>
            <div>
                DOB
            </div>
            <div>
                @Html.EditorFor(ModelItem => Model.DOB)
                <div id="lblError">
                </div>
            </div>
            <div>
                Age
            </div>
            <div>
                @*<div id="Age"></div>*@
                @Html.TextBoxFor(ModelItem => Model.Age, new { id = "Age" })
                @*<input type="text" id="Age" name="AgeMonth" />*@
            </div>
            <div>
                Occupation
            </div>
            <div>
                @Html.DropDownList("Occupation", ViewBag.Occupation as SelectList)
            </div>
            <div id="GrossSalary">
                <div>
                    GrossSalary
                </div>
                <div>
                    @Html.TextBoxFor(ModelItem => Model.GrossSalary)
                </div>
            </div>
            <div>
                <input type="submit" value="submit" />
            </div>
        </div>
    </div>
}

List View

@model IEnumerable<MVCDemo.Models.EmployeeMaster>
@{
    ViewBag.Title = "ListEmployees";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
    ListEmployees</h2>
<html>
<body>
<div>
    <input type="button" onclick="window.location.href='@Url.Action("Add")'" value="Add"/>
    @*<a href='@Url.Action("Add")' title="Add">Add</a>*@
</div>
    @if (Model.Count() > 0)
    {
        <table width = "100%">
            <tr>
                <td width="5%">
                   Code
                </td>
                <td width="10%">
                    Emp Name
                </td>
                <td width="5%">
                    Gender
                </td>
                <td width="10%">
                    Country
                </td>
                <td width="10%">
                    City
                </td>
                 <td width="10%">
                    DOB
                </td>
                <td width="20%">
                    Age
                </td>
                <td width="8%">
                    Aoccupation
                </td>
                 <td width="5%">
                    Edit
                </td>
                 <td width="5%">
                    Delete
                </td>
            </tr>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.EmpCode)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.EmpName)
                    </td>
                    <td>
                       @Html.DisplayFor(modelItem => item.Gender)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.CountryMaster.CountryName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.CityMaster.CityName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.DOB)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Age)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Occupation)
                    </td>
                    <td>
                        <a href = '@Url.Action("Edit", new { id = item.EmployeeId })' title="Add">Edit</a>
                    </td>
                    <td>
                        <a href = '@Url.Action("DeleteEmp", new { id = item.EmployeeId })' title="Add">Delete</a>
                    </td>
                </tr>
            }
        </table>
    }
</body>
</html>

Add,Edit,delete functionality in MVC (controller Detail)

AccountController

public class AccountController : Controller
    {
        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (new AccountRepository().AuthenticateUser(model.UserName, model.Password))
                    return RedirectToLocal(returnUrl);
                else
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
            return View(model);
        }

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            WebSecurity.Logout();

            return RedirectToAction("Index", "Home");
        }
}



Employee Controller

using MVCDemo.Repository;
using MVCDemo.Models;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace MVCDemo.Controllers
{
    public class EmployeeController : Controller
    {
        TestEntities _db = new TestEntities();
        public ActionResult ListEmployees()
        {
            var Emp = new EmployeeRepository().GetAllEmployee();
            return View(Emp);
        }


        public ActionResult Add()
        {
            fillGender(ViewBag, string.Empty);
            FillCountryDropDown(ViewBag, "--Select Country--");
            FillOccupation(ViewBag, "--Select Occupation--");
            return View();
        }

        public void fillGender(dynamic Viewbag, string SelectVal)
        {
            var Gender = new SelectList(new[]
                                            {   new {Value = "", Text = "--Select--"},
                                                new {Value = "0",Text = "Male"},
                                                new {Value = "1",Text = "FeMale"},
                                            }.ToList(), "Value", "Text", SelectVal);
            Viewbag.Gender = Gender;
        }

        public void FillOccupation(dynamic Viewbag, string SelectVal)
        {  

            var Occupation = new SelectList(new[]
                                                {
                                                    new {Value = "",Text="--Select Occupation--"},
                                                    new {Value ="Student",Text="Student"},
                                                    new {Value ="Job",Text="Job"},
                                                    new {Value ="Bussiness",Text="Bussiness"},
                                                }.ToList(), "Value", "Text",SelectVal);
            ViewBag.Occupation = Occupation;
        }

        public void FillCountryDropDown(dynamic Viewbag, string SelectVal)
        {
             var Country = (from c in _db.CountryMasters select c);
                         //orderby d.Name
                         //select d;
             ViewBag.Country = new SelectList(Country, "CountryId", "CountryName", SelectVal);
        }

        public ActionResult GetCity(int CountryId)
        {
            var City = (from c in _db.CityMasters where c.CountryId == CountryId select c);
            return Json(new SelectList(City.ToArray(), "CityId", "CityName"), JsonRequestBehavior.AllowGet);
           
        } 

        [HttpPost]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Add(EmployeeMaster emp)
        {
            if (new EmployeeRepository().SaveEmployee(emp))
            {
                 string strPath = Server.MapPath("~/Uploads");

                DirectoryInfo dir = new DirectoryInfo(strPath);
                if (!dir.Exists)
                {
                    dir.Create();
                } 


                var postedFileBase = Request.Files[0];
                if (postedFileBase != null && postedFileBase.FileName.Length > 0)
                {
                    string pic = System.IO.Path.GetFileName(postedFileBase.FileName);
                    string path = System.IO.Path.Combine(Server.MapPath("~/Uploads"), pic);
                    // file is uploaded
                    postedFileBase.SaveAs(path);
                }
                return RedirectToAction("ListEmployees");
            }
            return View();
        }


        public ActionResult Edit(int id = 0)
        {
            var emp = new EmployeeRepository().GetEmpByID(id);
            FillCountryDropDown(ViewBag, emp.CountryId.ToString());
            fillGender(ViewBag, emp.Gender);
            FillOccupation(ViewBag, emp.Occupation);
            ViewBag.CityId = emp.CityId;
            ViewBag.Occu = emp.Occupation;
            return View(emp);
        }

        [HttpPost]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(EmployeeMaster emp)
        {
            if (ModelState.IsValid)
            {
                if (new EmployeeRepository().SaveEmployee(emp))
                {
                    return RedirectToAction("ListEmployees");
                }
            }
            FillCountryDropDown(ViewBag, emp.CountryId.ToString());
            fillGender(ViewBag, emp.Gender);
            FillOccupation(ViewBag, emp.Occupation);
            return View(emp);
        }

        public ActionResult DeleteEmp(int id = 0)
        {
            if (new EmployeeRepository().DeleteEmp(id))
                return RedirectToAction("ListEmployees");
            return View();
        }

    }
}
 


Thursday, 24 October 2013

How to bind rediobutton in mvc 4

Controller Method to bind viewbag for gender redio button

 public void fillGender(dynamic Viewbag, string SelectVal)
{
            var Gender = new SelectList(new[]
                                            {   new {Value = "", Text = "--Select--"},
                                                new {Value = "0",Text = "Male"},
                                                new {Value = "1",Text = "FeMale"},
                                            }.ToList(), "Value", "Text", SelectVal);
            Viewbag.Gender = Gender;
}

View Page

 <div>
          Gender:
</div>
 <div>
         @Html.RadioButtonFor(model =model.Gender,           
          "Male", new { id = "male", @style = "width:0px;" })Male
</div>
<div>
         @Html.RadioButtonFor(model => model.Gender, "Female", new { id = "female", @style =          
         "width:0px;"})Female
</div>

Bind date textbox with datepicker and calculate age and display in textbox

Download jquery and css for datepicker from http://jqueryui.com/datepicker/

View Page
 =========Jquery functionfor datepicker==========
@Scripts.Render("~/bundles/Datepicker")
<link href="../../Scripts/Datepicker/jquery-ui.css" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript">
 var jqdatepicker = jQuery.noConflict();

    jqdatepicker(function () {
        jqdatepicker("#DOB").datepicker
            ({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'mm/dd/yy'
            });

    });

 function getAge(birthday) {

        if (birthday.value != '') {

            birthdayDate = new Date(birthday.value);
            dateNow = new Date();

            var years = dateNow.getFullYear() - birthdayDate.getFullYear();
            var months = dateNow.getMonth() - birthdayDate.getMonth();
            var days = dateNow.getDate() - birthdayDate.getDate();
            if (isNaN(years)) {

                document.getElementById('Age').value = '';
                document.getElementById('lblError').innerHTML = 'Input date is incorrect!';
                return false;

            }

            else {
                document.getElementById('lblError').innerHTML = '';

                if (months < 0 || (months == 0 && days < 0)) {

                    //alert(document.getElementById('Age'));
                    years = parseInt(years) - 1;
                    document.getElementById('Age').value = years + ' Years ' + months + ' Month'
                }
                else {
                    //alert(document.getElementById('Age').value);
                    document.getElementById('Age').value = years + ' Years ' + months + ' Month'
                }
            }
        }
    }
</script>
=========End=================
@using (Html.BeginForm("Add", "Employee", FormMethod.Post, new { id = "AddEmp" }))
{
            <div>
                DOB
            </div>
            <div>
                <input type="text" id="DOB" name="DOB" onblur="getAge(this)" />
                <div id="lblError">
                </div>
            </div>
}


Tuesday, 22 October 2013

Bind city dropdown on selection of country dropdownlist

Controller Action Method

public void FillCountryDropDown(dynamic Viewbag, string SelectVal)
             var Country = (from c in _db.CountryMasters select c);
             ViewBag.Country = new SelectList(Country, "CountryId", "CountryName", SelectVal);
}

public JsonResult GetCity(int CountryId)
 {
           var City = (from c in _db.CityMasters where c.CountryId == CountryId select c);
           return Json(new SelectList(City.ToArray(), "CityId", "CityName"), JsonRequestBehavior.AllowGet);
 } 

View Page

Script 
--------Script------
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.20.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
--------Script End------

Javascript
-------Javascript----------
<script language="javascript" type="text/javascript">
var createuser = jQuery.noConflict();
        createuser(function () {
            createuser("#CountryId").change(function () {
                var selectedItem = createuser(this).val();
                var ddlCities = createuser("#CityId");
                if (selectedItem.toString().length > 0 && parseInt(selectedItem) > 0) {
                    createuser.ajax({
                        cache: false,
                        type: "GET",
                        url: '@Url.Action("GetCity", "Employee")',
                        async: false,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: { "CountryId": selectedItem },
                        success: function (data) {
                            ddlCities.html('');
                            createuser.each(data, function (id, option) {
                                ddlCities.append(createuser('<option></option>').val(option.Value).html(option.Text));
                            });
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            alert('Failed to retrieve City.');
                        }
                    });
                }
                else {
                    ddlCities.html('');
                    ddlCities.append(createuser('<option></option>').val('').html('--Select City--'));
                }
            });
        });
</script>
 -------Javascript end----------

@using (Html.BeginForm("Add", "Employee", FormMethod.Post, new { id = "AddEmp" }))
{  
       <div>
               Country:
       </div>
        <div>
               @Html.DropDownList("CountryId", ViewBag.Country as SelectList, "--SelectCountry--")
        </div>
        <div>
                City:
        </div>
        <div>
               <select id="CityId" name = "CityId">
               </select>
        </div>

}

Note : In CountryDropDownList the name (here it is "CountryId") should be the name of the property in your model. and as city dropdown is getting bind according to country selection so we take <select> to bind city there give id and name with property of your model for city.(whatever is the name in your model for Country and city ids.)