Friday, 10 February 2017

MVC Json Ajax SQL multiple linked sorted dropdownlist








//JsonController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JsonSQL.sql_data;
using JsonSQL.Models;

namespace JsonSQL.Controllers
{
    public class JsonController : Controller
    {
        public countriesEntities db = new countriesEntities();

        public ActionResult Index()
        {
            var countries = db.countries.Select(x => new country_dto
            {id=x.id,country_name=x.country_name }).ToList();

            ViewBag.countries = new SelectList(countries.OrderBy(y => y.country_name), "id", "country_name");

            return View();
        }

        [HttpGet]
        public JsonResult Json_province(int id)
        {
            var provinces = db.provinces.Where(x => x.country_id == id).Select(y => new province_dto
            { id = y.id, country_id = (Int32)y.country_id, province_name = y.province_name }).ToList();

            return Json(provinces, JsonRequestBehavior.AllowGet);

        }

        [HttpGet]
        public JsonResult Json_city(int id)
        {
            var cities = db.cities.Where(x => x.province_id == id).Select(y => new city_dto
            { id = y.id, province_id=(Int32)y.province_id,city_name=y.city_name }).ToList();

            return Json(cities, JsonRequestBehavior.AllowGet);

        }

        [HttpPost]
        public ActionResult Location(string place)
        {
            return Content(place);
        }
    }
}

---------------------------------------------------------

//index.cshtml


@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<div class="form-horizontal">

    <div class="form-group">
        @Html.Label("countries", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("countries", null, htmlAttributes: new { @class = "form-control", onclick = "country_onchange()", onchange = "country_onchange()" })
        </div>
    </div>

    <div class="form-group">
        @Html.Label("provinces", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("provinces", Enumerable.Empty<SelectListItem>(), htmlAttributes: new { @class = "form-control", onchange = "province_onchange()" })
        </div>
    </div>

    <div class="form-group">
        @Html.Label("cities", htmlAttributes: new { @class = "text-mystyle col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("cities", Enumerable.Empty<SelectListItem>(), htmlAttributes: new { @class = "form-control", onchange = "city_onchange()" })
        </div>
    </div>
</div>


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

    function country_onchange() {
        //alert($("#countries option:selected").text());
        populate_province();

    }

    function province_onchange() {
        pupulate_city();
    }

    function city_onchange() {
        send_location();
    }

    function populate_province() {
        var country_id = $("#countries").val();

        $.ajax({
            url: '/Json/Json_province',
            type: "GET",
            data: { "id": country_id },
            success: function (result) {

                var result_sorted = result.sort(function (a, b) { return a.province_name.localeCompare(b.province_name); });

                var province_dropdownlist = document.getElementById("provinces");
                var city_dropdownlist = document.getElementById("cities");

                $(province_dropdownlist).empty();
                $(city_dropdownlist).empty();

                province_dropdownlist.options[0] = new Option("select province", 0);
                $(province_dropdownlist.options[0]).css("background-color", "#A6ACAF");

                $.each(result_sorted, function (index, value) {
                    province_dropdownlist.options[province_dropdownlist.length] = new Option(value.province_name, value.id);
                }
                );
            },
            error: function () {
                alert("Error");
            }
        });
    }

    function pupulate_city() {
        var province_id = $("#provinces").val();

        $.ajax({
            url: '/Json/Json_city',
            type: "GET",
            data: { "id": province_id },
            success: function (result) {

                var result_sorted = result.sort(function (a, b) { return a.city_name.localeCompare(b.city_name); });

                var city_dropdownlist = document.getElementById("cities");

                $(city_dropdownlist).empty();

                city_dropdownlist.options[0] = new Option("select city", 0);
                $(city_dropdownlist.options[0]).css("background-color", "#A6ACAF");

                $.each(result_sorted, function (index, value) {
                    city_dropdownlist.options[city_dropdownlist.length] = new Option(value.city_name, value.id);
                }
                );
            },
            error: function () {
                alert("Error");
            }
        });
    }

    function send_location() {

        var gps = $("#cities option:selected").text() + ", " + $("#provinces option:selected").text() + ", " + $("#countries option:selected").text();

        $.ajax({
            type: "POST",
            traditional: true,
            async: false,
            cache: false,
            url: '/Json/Location',
            context: document.body,
            data: { "place": gps },
            success: function (result) {
                //alert(result);
            },
            error: function (xhr) {
                //debugger;
                console.log(xhr.responseText);
                alert("Error has occurred..");
            }
        });
    }

</script>

//------------------------------------------------
//mystyle.css

body {
}

.text-mystyle{
    color:gold;
    font-weight: bold;
    font-size: 16px;
    text-align: right;
}

------------------------------------------------

Html color code:
http://htmlcolorcodes.com/

reference:
http://stackoverflow.com/questions/15640275/how-to-create-an-empty-dropdown-list-with-default-value
http://stackoverflow.com/questions/10289721/jquery-to-get-selectedtext-from-dropdown
http://stackoverflow.com/questions/227624/asp-net-mvc-controller-actions-that-return-json-or-partial-html
http://stackoverflow.com/questions/9909326/clear-dropdownlist-with-jquery
http://stackoverflow.com/questions/36332317/sort-by-alphabetical-order-in-javascript
http://stackoverflow.com/questions/32139216/change-color-of-option-in-select-element
http://stackoverflow.com/questions/16521565/html-select-with-different-background-color-for-every-option-that-works-properly

No comments:

Post a Comment