Sunday 5 February 2017

MVC Json/ajax/jquery dropdownlist get/post onchange onclick event

get data from JsonSend method in JsonController

dropdownbox onchange event: push uxDisplay string

submit button onclick event, alert data sent successfully

JsonReceive method in JsonController received posted Json Data


//JsonController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace WebApplication2.Controllers
{
    public class JsonController : Controller
    {
        // GET: Json
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult JsonReceive(List<string> JsonReceived)
        {
            //var js = new JavaScriptSerializer();
            //string JsonString = js.Deserialize<string>(JsonReceived);

            return Json(JsonReceived);
        }

        [HttpGet]
        public JsonResult JsonSend()
        {
            var cities = new List<string> { "Calgary", "Kelowna", "Toronto", "New York", "Montreal" };
            return Json(cities, JsonRequestBehavior.AllowGet);

        }
    }
}

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

//~/Views/Json/Index


@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<table class="table table-striped">
    <tr>
        <td class="col-md-2">City:</td>
        <td class="col-md-10"><select id="uxCities" /></td>
    </tr>
    <tr>
        <td colspan="2"><input type="button" id="uxSubmit" value="Submit" /></td>
    </tr>
</table>

<br />
<div id="uxDisplay">
</div>

<script src="~/Scripts/jquery-3.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
       $(document).ready(function()
       {
           //populateCities(cities);
           receiveJson(); //get data from controller

           //dropdownbox onchange event
           $("#uxCities").change(function () {
               //alert($("#uxCities").val());
               document.getElementById("uxDisplay").innerHTML += $("#uxCities").val() + " , ";
               JsonList.push($("#uxCities").val());
           });

           $("#uxSubmit").click(function () {
               sendJson(); //send data to controller
           });
       });

       var cities = new Array("Calgary", "Kelowna", "Toronto", "New York");
       var JsonList = [];
       //var JsonSend = JSON.stringify(JsonList);

       function populateCities(CityList) {
           var combo = document.getElementById("uxCities");
           $.each(CityList, function (index, city) {
               combo.options[combo.length] = new Option(city);
           });
       }

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

       function receiveJson() {
           var countryId = $('#country').val();
           //alert(countryId);
           $.ajax({
               url: '/Json/JsonSend',
               type: "GET",
               data: { },
               success: function (result) {
                   populateCities(result);
               },
               error: function () {
                   alert("Error");
               }
           });
       }

</script>


reference:
http://www.advancesharp.com/blog/1145/mvc-dropdownlistfor-fill-on-selection-change-of-another-dropdown
http://stackoverflow.com/questions/31059917/redirect-to-mvc-actionresult-with-parameters-when-dropdownlist-option-is-changed
http://stackoverflow.com/questions/1308339/create-a-one-to-many-relationship-using-sql-server
https://www.youtube.com/watch?v=h_ViuyVs4AE
http://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript
http://stackoverflow.com/questions/6456703/how-to-access-javascript-variable-within-url-action
http://www.c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in-mvc/
https://forums.asp.net/t/1905522.aspx?How+to+use+javascript+in+MVC+view+
http://stackoverflow.com/questions/36469906/getting-data-from-controller-using-ajax-in-asp-net-mvc

No comments:

Post a Comment