Wednesday, November 5, 2014

MVC Entity Frame work



Web grig
@model IEnumerable<WebGridIEditUpdate.Models.Job>

@{
    ViewBag.Title = "Index";

    WebGrid grid = new WebGrid(Model, canSort: true);
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
@grid.GetHtml(
       
         headerStyle: "header", //applying style.
         tableStyle: "table",
         footerStyle: "grid-footer",
         //tableStyle: "grid",
         fillEmptyRows: false,
         // headerStyle: "gvHeading",
         alternatingRowStyle: "gvAlternateRow",
         rowStyle: "gvRow",
         //footerStyle: "gvFooter",

         mode: WebGridPagerModes.All,
         firstText: "<< First",
         previousText: "< Prev",
         nextText: "Next >",
         lastText: "Last >>",
         columns: new[] {
         grid.Column("Id",header: "ID"),
         grid.Column("Title",header: "Title"),
         grid.Column("Salary"),
         grid.Column("CountryId"),
         grid.Column(header: "Action",format:@<text><a href="/Jobs/Edit/@item.Id" id="Edit_@item.Id" class="edit">Edit</a>
         <a href="/Jobs/Edit/@item.Id" id="Update_@item.Id" style="display:none" class="update">Update</a><a href="/Jobs/Edit/@item.Id" id="Cancel_@item.Id" style="display:none" class="cancel">Cancel</a>
         <a href="/Jobs/Delete/@item.Id" id="Delete_@item.Id" class="delete">Delete</a></text>),
         grid.Column("Detail", format: @<text>@Html.ActionLink("Edit", "Edit", new { id = item.Id }) </text>),
         grid.Column("",style: "col1",format: @<text>
         <button class="edit-book display-mode" id="@item.Id">Edit</button>
         <button class="save-book edit-mode" id="@item.Id">Save</button></text>),



}
             )



  



DropDownlist
Posted by Vijay Saklani on 2:26 PM with 11 comments
Introduction: In this article today I am going to explain how we can Populate Cascading Dropdown List in Asp.net MVC4 using Json and Jquery
Populate Cascading Dropdown
(Click to Enlarge)
Description:

I want to populate State dropdown on Country selection and on State Dropdown Selection populate City dropdown. I have three classes in model Country, State and City.
Country:
using System.ComponentModel.DataAnnotations;

public class Country
    {
        [Key]
        public int CountryId { get; set; }
        public string CountryName { get; set; }

        public virtual ICollection<State> States { get; set; }
    }

State:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;


public class State
    {
        [Key]
        public int StateId { get; set; }
        public string StateName { get; set; }
        [ForeignKey("Country")]
        public int CountryId { get; set; }

        public virtual Country Country { get; set; }
        public virtual ICollection<City> Citys { get; set; }
    }
City:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;


public class City
    {
        [Key]
        public int CityId { get; set; }
        public string CityName { get; set; }
        [ForeignKey("State")]
        public int StateId { get; set; }

        public virtual State State { get; set; }
    }
After that I add a new Empty MVC Controller to project.
Populate Cascading Dropdown
                                                                   (Click to Enlarge)
Write the given code:

using MVCAPPLICATION.Models;

private ProjectContext db = new ProjectContext();
public ActionResult Index()
        {
            ViewBag.CountryId = new SelectList(db.Countrys, "CountryId", "CountryName");
            return View();
        }
        public JsonResult StateList(int Id)
        {
            var state = from s in db.States
                           where s.CountryId == Id
                           select s;
            return Json(new SelectList(state.ToArray(), "StateId", "StateName"), JsonRequestBehavior.AllowGet);
        }

        public JsonResult Citylist(int id)
        {
            var city = from c in db.Citys
                       where c.StateId == id
                       select c;
            return Json(new SelectList(city.ToArray(), "CityId", "CityName"), JsonRequestBehavior.AllowGet);
        }
        public IList<State> Getstate(int CountryId)
        {
            return db.States.Where(m => m.CountryId == CountryId).ToList();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadClassesByCountryId(string CountryName)
        {
            var stateList = this.Getstate(Convert.ToInt32(CountryName));
            var stateData = stateList.Select(m => new SelectListItem()
            {
                Text = m.StateName,
                Value = m.CountryId.ToString(),
            });
            return Json(stateData, JsonRequestBehavior.AllowGet);
        }

Now add a Empty view for Controller.

@model MVCAPPLICATION.Models.ProjectContext

@using (Html.BeginForm())
{
@Html.DropDownList("Country", ViewBag.CountryId as SelectList, "Select a Country", new { id="Country" })<br />
    <select id="State" name="state"></select><br />
    <select id="city" name="City"></select><br />
}

Add Jquery to view:
@Scripts.Render("~/bundles/jquery")
<script type="text/jscript">
    $(function () {
        $('#Country').change(function () {
            $.getJSON('/Cascading/StateList/' + $('#Country').val(), function (data) {
                var items = '<option>Select a State</option>';
                $.each(data, function (i, state) {
                    items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
                });
                $('#State').html(items);
            });
        });
       
        $('#State').change(function () {
            $.getJSON('/Cascading/Citylist/' + $('#State').val(), function (data) {
                var items = '<option>Select a City</option>';
                $.each(data, function (i, city) {
                    items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
                });
                $('#city').html(items);
            });
        });
    });
</script>

Build and run the project.
Is this article helpful for you?
Controller  Working CaseCading Dropdownlist
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DropDownList.Controllers
{
    public class CountryController : Controller
    {
        // GET: Country
        public ActionResult Index()
        {
            List<SelectListItem> li = new List<SelectListItem>();

            li.Add(new SelectListItem { Text = "Select", Value = "0" });

            li.Add(new SelectListItem { Text = "India", Value = "1" });

            li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });

            li.Add(new SelectListItem { Text = "China", Value = "3" });

            li.Add(new SelectListItem { Text = "Austrila", Value = "4" });

            li.Add(new SelectListItem { Text = "USA", Value = "5" });

            li.Add(new SelectListItem { Text = "UK", Value = "6" });

            ViewData["country"] = li;

            return View();
        }
        public JsonResult GetStates(string id)
        {

            List<SelectListItem> states = new List<SelectListItem>();

            switch (id)
            {

                case "1":

                    states.Add(new SelectListItem { Text = "Select", Value = "0" });

                    states.Add(new SelectListItem { Text = "ANDAMAN & NIKOBAR ISLANDS", Value = "1" });

                    states.Add(new SelectListItem { Text = "ANDHRA PRADESH", Value = "2" });

                    states.Add(new SelectListItem { Text = "ARUNACHAL PRADESH", Value = "3" });

                    states.Add(new SelectListItem { Text = "ASSAM", Value = "4" });

                    states.Add(new SelectListItem { Text = "BIHAR", Value = "5" });

                    states.Add(new SelectListItem { Text = "CHANDIGARH", Value = "6" });

                    states.Add(new SelectListItem { Text = "CHHATTISGARH", Value = "7" });

                    states.Add(new SelectListItem { Text = "DADRA & NAGAR HAVELI", Value = "8" });

                    states.Add(new SelectListItem { Text = "DAMAN & DIU", Value = "9" });

                    states.Add(new SelectListItem { Text = "GOA", Value = "10" });

                    states.Add(new SelectListItem { Text = "GUJARAT", Value = "11" });

                    states.Add(new SelectListItem { Text = "HARYANA", Value = "12" });

                    states.Add(new SelectListItem { Text = "HIMACHAL PRADESH", Value = "13" });

                    states.Add(new SelectListItem { Text = "JAMMU & KASHMIR", Value = "14" });

                    states.Add(new SelectListItem { Text = "JHARKHAND", Value = "15" });

                    states.Add(new SelectListItem { Text = "KARNATAKA", Value = "16" });

                    states.Add(new SelectListItem { Text = "KERALA", Value = "17" });

                    states.Add(new SelectListItem { Text = "LAKSHADWEEP", Value = "18" });

                    states.Add(new SelectListItem { Text = "MADHYA PRADESH", Value = "19" });

                    states.Add(new SelectListItem { Text = "MAHARASHTRA", Value = "20" });

                    states.Add(new SelectListItem { Text = "MANIPUR", Value = "21" });

                    states.Add(new SelectListItem { Text = "MEGHALAYA", Value = "22" });

                    states.Add(new SelectListItem { Text = "MIZORAM", Value = "23" });

                    states.Add(new SelectListItem { Text = "NAGALAND", Value = "24" });

                    states.Add(new SelectListItem { Text = "NCT OF DELHI", Value = "25" });

                    states.Add(new SelectListItem { Text = "ORISSA", Value = "26" });

                    states.Add(new SelectListItem { Text = "PUDUCHERRY", Value = "27" });

                    states.Add(new SelectListItem { Text = "PUNJAB", Value = "28" });

                    states.Add(new SelectListItem { Text = "RAJASTHAN", Value = "29" });

                    states.Add(new SelectListItem { Text = "SIKKIM", Value = "30" });

                    states.Add(new SelectListItem { Text = "TAMIL NADU", Value = "31" });

                    states.Add(new SelectListItem { Text = "TRIPURA", Value = "32" });

                    states.Add(new SelectListItem { Text = "UTTAR PRADESH", Value = "33" });

                    states.Add(new SelectListItem { Text = "UTTARAKHAND", Value = "34" });

                    states.Add(new SelectListItem { Text = "WEST BENGAL", Value = "35" });

                    break;

                case "UK":

                    break;

                case "India":

                    break;

            }

            return Json(new SelectList(states, "Value", "Text"));

        }
        public JsonResult GetCity(string id)
        {

            List<SelectListItem> City = new List<SelectListItem>();

            switch (id)
            {

                case "2":

                    City.Add(new SelectListItem { Text = "Select", Value = "0" });

                    City.Add(new SelectListItem { Text = "Hyderabad", Value = "1" });

                    City.Add(new SelectListItem { Text = "Warangal", Value = "2" });

                    City.Add(new SelectListItem { Text = "Karimager", Value = "3" });

                    City.Add(new SelectListItem { Text = "RangaReddy", Value = "4" });

                    City.Add(new SelectListItem { Text = "Nalgonda", Value = "5" });

                    City.Add(new SelectListItem { Text = "Khammam", Value = "6" });

                    break;

            }



            return Json(new SelectList(City, "Value", "Text"));

        }
    }
}
Index
@{
    ViewBag.Title = "Index";
}

<h2>Country</h2>


@section scripts{<script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>

<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>

<script type="text/javascript">

    $(document).ready(function () {
        //alert('hiiii');
        //Dropdownlist Selectedchange event

        $("#Country").change(function () {

            $("#State").empty();

            $.ajax({
               
                type: 'POST',

                url: '@Url.Action("GetStates")', // we are calling json method
              
                dataType: 'json',

                data: { id: $("#Country").val() },

               // here we are get value of selected country and passing same value


                success: function (states) {

                    // states contains the JSON formatted list

                    // of states passed from the controller

                    $.each(states, function (i, state) {

                    $("#State").append('<option value="' + state.Value + '">' +

                         state.Text + '</option>');

                    // here we are adding option for States

                    });

                },

                error: function (ex) {

                    alert('Failed to retrieve states.' + ex);

                }

            });

            return false;

        })

    });



    $(document).ready(function () {

        //Dropdownlist Selectedchange event

        $("#State").change(function () {

            $("#city").empty();

            $.ajax({

                type: 'POST',

                url: '@Url.Action("GetCity")',

                dataType: 'json',

                data: { id: $("#State").val() },

                success: function (citys) {

                    // states contains the JSON formatted list

                    // of states passed from the controller

                    $.each(citys, function (i, city) {

                        $("#city").append('<option value="' + city.Value + '">' + city.Text + '</option>');

                    });

                },

                error: function (ex) {

                    alert('Failed to retrieve states.' + ex);

                }

            });

            return false;

        })

    });

</script>
}

@using (Html.BeginForm())
{
    <div>

        @Html.DropDownList("Country", ViewBag.CountryId as SelectList, new { id = "Country" })<br />
        @*@Html.DropDownList("Countries", ViewData["country"] as List<SelectListItem>)*@

        @* @Html.DropDownList("state",ViewBag.States as SelectList,"Please select",new { id = "state" })*@
    </div>
    <div>
        @*@Html.DropDownList("Countries", ViewData["country"] as List<SelectListItem>)*@
    </div>

    <div>
        @*@Html.DropDownList("State", new SelectList(string.Empty), "Select A State", new { id = "State" })<br />*@
        @Html.DropDownList("State", new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { style = "width:250px", @class = "dropdown1" })
    </div>
    <div>
        @Html.DropDownList("city", new SelectList(string.Empty, "Value", "Text"), "Please select a city", new { style = "width:250px", @class = "dropdown1" })

    </div>
}
GetState

@{
    ViewBag.Title = "GetStates";
}

<h2>GetStates</h2>

<script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>

<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>

<script type="text/javascript">

    $(document).ready(function () {
        alert('hiiii');
        //Dropdownlist Selectedchange event

        $("#Country").change(function () {

            $("#State").empty();

            $.ajax({

                type: 'POST',

                url: '@Url.Action("GetStates")', // we are calling json method

                dataType: 'json',

                data: { id: $("#Country").val() },

               // here we are get value of selected country and passing same value

                success: function (states) {

                    // states contains the JSON formatted list

                    // of states passed from the controller

                    $.each(states, function (i, state) {

                    $("#State").append('<option value="' + state.Value + '">' +

                         state.Text + '</option>');

                    // here we are adding option for States



                    });

                },

                error: function (ex) {

                    alert('Failed to retrieve states.' + ex);

                }

            });

            return false;

        })

    });

</script>


Get City

@{
    ViewBag.Title = "GetCity";
}

<h2>GetCity</h2>

<script type="text/javascript">

    $(document).ready(function () {

        //Dropdownlist Selectedchange event

        $("#State").change(function () {

            $("#city").empty();

            $.ajax({

                type: 'POST',

                url: '@Url.Action("GetCity")',

                dataType: 'json',

                data: { id: $("#State").val() },

                success: function (citys) {

                    // states contains the JSON formatted list

                    // of states passed from the controller

                    $.each(citys, function (i, city) {

                        $("#city").append('<option value="'+ city.Value + '">'+ city.Text + '</option>');

                    });

                },

                error: function (ex) {

                    alert('Failed to retrieve states.' + ex);

                }

            });

            return false;

        })

    });

</script>