Monday, 19 October 2015

example of cascading dropdown in knockout,MVC & MVVM

Controller :


using System;


using System.Collections.Generic;


using System.Linq;


using System.Web;


using System.Web.Mvc;


using MvcApplication1.Models;


namespace MvcApplication1.Controllers






{


public class HomeController : Controller





{


//


// GET: /Home/

public ActionResult Index()






{


return View();






}


public JsonResult Getc()






{


using (Database1Entities obj = new Database1Entities())






{


return Json(obj.COUNTRies.ToList(), JsonRequestBehavior.AllowGet);






}


}


public JsonResult Gets(int cid)






{


using (Database1Entities obj = new Database1Entities())






{


return Json(obj.STATEs.Where(m=>m.CID==cid).ToList(), JsonRequestBehavior.AllowGet);






}


}


}


}



View :


@{


ViewBag.Title = "Index";






}


<link href="~/bootstrap-3.3.5-dist/bootstrap-3.3.5-dist/css/bootstrap.min.css" rel="stylesheet" />

<link href="~/bootstrap-3.3.5-dist/bootstrap-3.3.5-dist/css/bootstrap-theme.min.css" rel="stylesheet" />

<script src="~/Scripts/jquery-2.1.4.min.js"></script>

<script src="~/Scripts/knockout-3.3.0 (1).js"></script>

<div class="container">


<form class="form-horizontal">


<div class="form-group">


<label class="col-lg-3 control-label">CONUNTRY</label>


<div class="col-lg-9">


<select class="form-control" data-bind="options:ddl,optionsCaption:'Select', optionsText:'CNAME', optionsValue:'CID', value:EMP.CID"></select>


</div>


</div>


<div class="form-group">


<label class="col-lg-3 control-label">STATE</label>


<div class="col-lg-9">


<select class="form-control" data-bind="options:sddl,optionsCaption:'Select', optionsText:'SNAME', optionsValue:'SID', value:EMP.SID"></select>


</div>


</div>


<div class="form-group">


<label class="col-lg-3 control-label"></label>


<div class="col-lg-9">


<input type="button" value="Display" class="btn btn-primary" data-bind="click:save" />


</div>


</div>


</form>

</div>

<script type="text/javascript">


$(function () {

function emp()






{


var self = this;






self.CID = ko.observable();


self.SID = ko.observable();


}


function x()






{


var self = this;

self.EMP = new emp();






self.ddl = ko.observableArray();


self.sddl = ko.observableArray();


self.g = ko.observable();


self.y = ko.observable();


$.ajax({


url: '/Home/Getc',

type: 'Get',

cache:false,

success: function (data)






{


self.ddl(data);


}


});





self.EMP.CID = ko.dependentObservable({


read: self.y,


write: function (t)






{


self.g(t);


$.ajax({


url: '/Home/Gets',

type: 'post',






data:{cid:t},


cache: false,

success: function (data) {






self.sddl(data);


}


});


}


});





self.save = function ()






{


alert(self.g());


alert(self.EMP.SID());


}


}


ko.applyBindings(new x());






});


</script>





 

No comments:

Post a Comment