Insert Multiple rows in Kendo Grid on load without for loop - asp.net-mvc

I need to Display 100 empty rows in Kendo grid on load as shown here Image without using for loop.
I have tried this:-
$(document).ready(function () {
var grid = $("#AlertRowGrid").data("kendoGrid");
var datasource = grid.dataSource;
for (i = 0; i < 100; i++) {
datasource.add({ PhoneNumber: '', Field1: '', Field2: '', Field3: '', Field4: '', Field5: '', Field6: '', Field7: '', Field8: '', Field9: '', Field10: '' });
}
});
But using for loop consumes much loading time.So is there any better option other than for loop to display multiple rows in kendo grid?
My grid is as below:-
#(Html.Kendo().Grid<SCC.Business.Models.Point_of_Service.Custom.SendAlertsDataModel>()
.Name("AlertRowGrid")
.Columns(columns =>
{
columns.Bound(c => c.PhoneNumber).ClientTemplate("<input type='text' value='#:PhoneNumber#' id='Phone' maxlength='12' onchange = EditGridRow(this) placeholder = '000-000-0000' class='MaskPhone'/>").Title(General.PhoneNumber).Width("10%").HtmlAttributes(new { #class = "PhoneNumber" });
columns.Bound(c => c.Field1).ClientTemplate("<input type='text' value='#:Field1#' id='Field1' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field1).Width("10%").HtmlAttributes(new { #class = "Field1" });
columns.Bound(c => c.Field2).ClientTemplate("<input type='text' value='#:Field2#' id='Field2' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field2).Width("10%").HtmlAttributes(new { #class = "Field2" });
columns.Bound(c => c.Field3).ClientTemplate("<input type='text' value='#:Field3#' id='Field3' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field3).Width("10%").HtmlAttributes(new { #class = "Field3" });
columns.Bound(c => c.Field4).ClientTemplate("<input type='text' value='#:Field4#' id='Field4' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field4).Width("10%").HtmlAttributes(new { #class = "Field4" });
columns.Bound(c => c.Field5).ClientTemplate("<input type='text' value='#:Field5#' id='Field5' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field5).Width("10%").HtmlAttributes(new { #class = "Field5" });
columns.Bound(c => c.Field6).ClientTemplate("<input type='text' value='#:Field4#' id='Field4' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field6).Width("10%").HtmlAttributes(new { #class = "Field6" });
columns.Bound(c => c.Field7).ClientTemplate("<input type='text' value='#:Field7#' id='Field7' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field4).Width("10%").HtmlAttributes(new { #class = "Field7" });
columns.Bound(c => c.Field8).ClientTemplate("<input type='text' value='#:Field8#' id='Field8' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field8).Width("10%").HtmlAttributes(new { #class = "Field8" });
columns.Bound(c => c.Field4).ClientTemplate("<input type='text' value='#:Field9#' id='Field9' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field9).Width("10%").HtmlAttributes(new { #class = "Field9" });
columns.Bound(c => c.Field10).ClientTemplate("<input type='text' value='#:Field10#' id='Field10' maxlength='100' onchange = EditGridRow(this) />").Title(PointOfService.SendAlert_Field4).Width("10%").HtmlAttributes(new { #class = "Field10" });
}).Scrollable(x => x.Height(400)).Events(e => e.DataBound("onDataBound"))
)
Your help will be appreciated Thanks.

Every time you update the grid's data source, it gets refreshed. I've changed your code to build the data source first and assign it to the grid afterwards:
$(document).ready(function () {
console.log("S: " + new Date());
var data = [];
for (var i = 0; i < 100; i++) {
data.push({ PhoneNumber: '', Field1: '', Field2: '', Field3: '', Field4: '', Field5: '', Field6: '', Field7: '', Field8: '', Field9: '', Field10: '' });
}
var dataSource = new kendo.data.DataSource({
data: data
});
var grid = $("#AlertRowGrid").getKendoGrid();
grid.setDataSource(dataSource);
grid.dataSource.read();
console.log("E: " + new Date());
});
According to https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/setdatasource it should not be necessary to reload the data source manually. But it did not work without.
Your code took 5 seconds on my machine. Now it is less than a second.

Related

Kendo UI Grid - Show row number

How do I show the row number in a Kendo UI Grid? The code I have is not working. The page displays the column but it's empty.
#{int counter = 1;}
#(Html.Kendo().Grid<QueueViewModel>()
.Name("Queue")
.Columns(columns =>
{
columns.Template(#<text><span>#counter #{ counter++; }</span></text>).Title("#");
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Read(read => read.Action("GetOpenQueue", "DataSource", new { GeneralQueue = true })
))
Do this:
#{
int counter = 1;
}
#(Html.Kendo().Grid<QueueViewModel>()
.Name("Queue")
.Columns(columns =>
{
columns.Template(#<text><span>#(counter++)</span></text>).Title("#");
})
Or, if your DataSource is set to Ajax (client-side), do this:
<script>
var counter = 1;
function onDataBound(e) {
counter = 1;
}
function renderNumber(data) {
return counter++;
}
</script>
#(Html.Kendo().Grid()
.Name("Queue")
.Columns(columns => {
columns.Template(t => { }).ClientTemplate("#= renderNumber(data) #").Title("#");
})
.Events(ev => ev.DataBound("onDataBound"))
)
Column ClientTemplate is client-side functionality. You cannot use server-side variables in it. You should define Javascript variable:
<script>
var i = 1;
</script>
Then, inside the grid use this:
columns.Template(t => { }).ClientTemplate(#=i++#).Title("#");
Updated: it should be ClientTemplate instead of Template
Try this way In javascript, the code will support the paging also
<script type="text/javascript">
var CountIt = 0
function GetCountIt() {
var page = $("#YourGrid").data("kendoGrid").dataSource.page();
var pageSize = $("#YourGrid").data("kendoGrid").dataSource.pageSize();
CountIt++;
return (page * pageSize) - pageSize + CountIt
}
function YourGrid_DataBound() {
CountIt = 0; $('#YourGrid').data('kendoGrid').pager.unbind("change").bind('change', function (e) {
CountIt = 0
})
}
</script>
then add to your kindo grid
.Events(events =>
{
events.DataBound("YourGrid_DataBound");
})
.Columns(columns =>
{
columns.Bound("").ClientTemplate("#=GetCountIt()#").Title("Sr.").Width(50);
...

Get selected column information in Kendo UI grid

I have one requirement for asp.net MVC application and for that inside Kendo UI grid, I have customized one column with combo box and two buttons for performing adding or deletion of any user selected value or manual typed value from combo box control.
But I am not able to get how I can get button click information for any specific row of that column.
Kindly guide how I can achieve such kind of behavior.
Sample Code for Grid is below and I want to get clickable for Category Column.
#(Html.Kendo().Grid<GridHeaderTemplate.Models.ProductModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.ProductName);
columns.ForeignKey(p => p.CategoryID, (System.Collections.IEnumerable)ViewData["categories"], "CategoryID", "CategoryName")
.Title("Category").HtmlAttributes(new
{
#class = "templateCell"
}).ClientTemplate("<table cellspacing='0' class='data-row data-personal'><tr>" +
"<td>#=data.Category.CategoryName# <span class='custom-arrow k-icon k-i-arrow-s'></span></td>" +
"<td><button id='customButton'>Add</button> <span></span> <button id='customButton1'>Delete</button></td>" +
"</tr></table>")
.HeaderTemplate(
#<text>
<table cellspacing="0" class="data-header">
<tr>
<td colspan="2"><strong>Category</strong></td>
</tr>
<tr>
<td>Category Name</td>
<td>Settings</td>
</tr>
</table>
</text>
)
.Width(300);//.ClientTemplate("#=data.Category.CategoryName# <span class='custom-arrow k-icon k-i-arrow-s'></span>"); ;
columns.Bound(p => p.UnitPrice).Width(150);
columns.Command(command => command.Destroy()).Width(110);
})
.ToolBar(toolBar =>
{
toolBar.Save();
toolBar.Create();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Filterable()
.Groupable()
.Pageable()
.Scrollable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Model(model =>
{
model.Id(p => p.ProductID);
model.Field(p => p.ProductID).Editable(false);
model.Field(p => p.CategoryID).DefaultValue(1);
})
Enter some code to help us helping you..
You need to have in your object the Id that you want to add or delete,
If you created a client template adding the two specific buttons and calling a javascript function, then you have acess to the properties of the row
for instance:
column.Bound(c=>c.Id).hidden(true);
column.Bound(c=>c.Name).ClientTemplate("<span onclick='AddToThisId(#=Id#)'>add</span>");
Edited:
CONTROLLER:
public ActionResult Delete(int id)
{
try
{
//Delete....
}
catch (Exception ex)
{
result.SetInsucess("Erro a apagar registo: " + ex.Message + ".");
}
return Json(true, JsonRequestBehavior.AllowGet);
}
VIEW
<script>
function AddSomethingBaseOnId(id){
$.ajax({
cache: false,
type: 'GET',
data: { Id: Id },
contentType: "application/json",
url: "Controller/AddAction",
success: function (data) {
alert("sucess");
},
fail: function (jqXHR, textStatus) {
alert("Ocorreu um erro: " + textStatus);
$("#" + uid).hide();
}
});
}
function DeleteSomethingBaseOnId(id){
$.ajax({
cache: false,
type: 'GET',
data: { Id: Id },
contentType: "application/json",
url: "Controller/DeleteAction",
success: function (data) {
alert("sucess");
},
fail: function (jqXHR, textStatus) {
alert("Ocorreu um erro: " + textStatus);
$("#" + uid).hide();
}
});
}
</script>
in your client template:
"<td>#=data.Category.CategoryName# <span class='custom-arrow k-icon k-i-arrow-s'></span></td>" +
"<td><button id='customButton' onclick="AddSomethingBaseOnId(#=data.Id#)">Add</button> <span></span> <button id='customButton1' onclick="DeleteSomethingBaseOnId(#=data.Id#)">Delete</button></td>" +

Cannot export hidden columns in Kendo Grid

I want to hide some columns on Kendo Grid and export them to the excel as the visible columns. However, using Hidden(true) or Visible(false) does not make any sense and these fields are not exported. The workarounds on this page is not working. Any idea?
View:
#(Html.Kendo().Grid<ContactViewModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(m => m.NameSurname).Title("Name Surname").Width("%100");
columns.Bound(m => m.InstituteName).Title("Institute Name").Width("250px");
columns.Bound(m => m.CityName).Title("City").Width("145px");
columns.Bound(m => m.RegionName).Title("Region").Width("145px");
columns.Bound(m => m.ContactMobile).Title("Mobile").Width("125px");
columns.Bound(m => m.ContactAddress).Title("Address").Hidden(true); //I want to export these fields
columns.Bound(m => m.ContactAddress).Title("Address").Visible(false); //I want to export these fields
})
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
<button class="btn btn-primary btn-xs pull-right k-button k-button-icontext k-grid-excel">
<span class="k-icon k-excel"></span>
Liste (xls)
</button>
</div>
</text>);
})
.Excel(excel => excel
.FileName("List.xlsx")
.Filterable(true)
.AllPages(true)
.ProxyURL(Url.Action("Excel_Export_Save", "Controller"))
)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Index_Read", "Controller"))
.ServerOperation(false)
.PageSize(12)
)
)
)
See this solution Plunker, suggested solution on Telerik website.
To show column in your export functionality, bind this 'excelExport' event of that grid.
var exportFlag = false;
$("#grid").data("kendoGrid").bind("excelExport", function (e) {
if (!exportFlag) {
// e.sender.showColumn(0); for demo
// for your case show column that you want to see in export file
e.sender.showColumn(5);
e.sender.showColumn(6);
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
e.sender.hideColumn(5);
e.sender.hideColumn(6);
exportFlag = false;
}
});
Demo: Hide First column and show in export file
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/grid/excel-export">
<style>
html {
font-size: 12px;
font-family: Arial, Helvetica, sans-serif;
}
</style>
<title></title>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.material.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.dataviz.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.dataviz.material.min.css" />
<script src="http://cdn.kendostatic.com/2015.1.318/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.318/js/jszip.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.318/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div id="grid" style="width: 900px"></div>
<script>
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
fileName: "Kendo UI Grid Export.xlsx",
proxyURL: "http://demos.telerik.com/kendo-ui/service/export",
filterable: true
},
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
},
schema: {
model: {
fields: {
UnitsInStock: {
type: "number"
},
ProductName: {
type: "string"
},
UnitPrice: {
type: "number"
},
UnitsOnOrder: {
type: "number"
},
UnitsInStock: {
type: "number"
}
}
}
},
pageSize: 7
},
sortable: true,
pageable: true,
columns: [{
width: "10%",
field: "ProductName",
title: "Product Name",
hidden: true
}, {
width: "10%",
field: "UnitPrice",
title: "Unit Price"
}, {
width: "10%",
field: "UnitsOnOrder",
title: "Units On Order"
}, {
width: "10%",
field: "UnitsInStock",
title: "Units In Stock"
}]
});
var exportFlag = false;
$("#grid").data("kendoGrid").bind("excelExport", function (e) {
if (!exportFlag) {
e.sender.showColumn(0);
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
e.sender.hideColumn(0);
exportFlag = false;
}
});
</script>
</div>
</body>
</html>
I try with this example also, it is same as my previous answer just jQuery binding event will be different.
You just need to do changes in code by adding grid event Events(x => x.ExcelExport("excelExport")) and jQuery function excelExport(e) {}.
Also use only Hidden(true) to hide grid column.
ViewModel is something like this :
public class ContactViewModel
{
public string NameSurname { get; set; }
public string InstituteName { get; set; }
public string CityName { get; set; }
public string RegionName { get; set; }
public string ContactMobile { get; set; }
public string ContactAddress { get; set; }
}
Controller will be:
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Index_Read([DataSourceRequest]DataSourceRequest request)
{
var listOfContactViewModel = new List<ContactViewModel>() {
new ContactViewModel(){ NameSurname = "N1", InstituteName = "I1", CityName ="C1",RegionName = "R1",ContactMobile = "M1", ContactAddress = "C1" },
new ContactViewModel(){ NameSurname = "N2", InstituteName = "I2", CityName ="C2",RegionName = "R2",ContactMobile = "M2", ContactAddress = "C2" },
new ContactViewModel(){ NameSurname = "N3", InstituteName = "I3", CityName ="C3",RegionName = "R3",ContactMobile = "M3", ContactAddress = "C3" },
new ContactViewModel(){ NameSurname = "N4", InstituteName = "I4", CityName ="C4",RegionName = "R4",ContactMobile = "M4", ContactAddress = "C4" },
new ContactViewModel(){ NameSurname = "N5", InstituteName = "I5", CityName ="C5",RegionName = "R5",ContactMobile = "M5", ContactAddress = "C5" }
};
return Json(listOfContactViewModel.ToDataSourceResult(request),JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Excel_Export_Save(string contentType, string base64, string fileName)
{
var fileContents = Convert.FromBase64String(base64);
return File(fileContents, contentType, fileName);
}
}
And View for this:
<h2>Index</h2>
#(Html.Kendo().Grid<KendoUIMVC5.Models.ContactViewModel>()
.Name("Grid")
.Events(x => x.ExcelExport("excelExport"))
.Columns(columns =>
{
columns.Bound(m => m.NameSurname).Title("Name Surname").Width("%100");
columns.Bound(m => m.InstituteName).Title("Institute Name").Width("250px");
columns.Bound(m => m.CityName).Title("City").Width("145px");
columns.Bound(m => m.RegionName).Title("Region").Width("145px");
columns.Bound(m => m.ContactMobile).Title("Mobile").Width("125px");
columns.Bound(m => m.ContactAddress).Title("Address").Hidden(true); //I want to export these fields
columns.Bound(m => m.ContactAddress).Title("Address").Hidden(false); //I want to export these fields
})
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
<button class="btn btn-primary btn-xs pull-right k-button k-button-icontext k-grid-excel">
<span class="k-icon k-excel"></span>
Liste (xls)
</button>
</div>
</text>);
})
.Excel(excel => excel
.FileName("List.xlsx")
.Filterable(true)
.AllPages(true)
.ProxyURL(Url.Action("Excel_Export_Save", "Test"))
)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Index_Read", "Test"))
.ServerOperation(false)
.PageSize(12)
)
)
<script type="text/javascript">
var exportFlag = false;
function excelExport(e)
{
if (!exportFlag) {
e.sender.showColumn(5);
e.sender.showColumn(6);
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
e.sender.hideColumn(5);
e.sender.hideColumn(6);
exportFlag = false;
}
}
</script>
...
columns.Bound(x => x.Id).Visible(false);
columns.Bound(x => x.Siege).Width(150);
columns.Bound(x => x.Societe).Width(150);
columns.Bound(x => x.Matricule).Width(100).Hidden(true);
columns.Bound(x => x.Civilite).Width(80);
...
var exportFlag = false;
$("#myGrid").data("kendoGrid").bind("excelExport", function (e) {
var grid = e.sender;
var columns = grid.columns;
if (!exportFlag) {
$.each(columns, function (index, value) {
var col = this;
if (col.hidden == true) {
col.hidden = false;
}
});
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
}
else {
$.each(columns, function (index, value) {
var col = this;
if (col.hidden == false) {
col.hidden = true;
}
});
exportFlag = false;
}
});

Kendo UI Grid in a Splitter

I've got a splitter in my layout, to display informations.
My display is good, but when I had my grid in my index.html (which is called in my layout by #RenderBody() ) , my splitter isn't well displayed anymore ...
Everything is on a single page, without splitter ...
Any ideas ?
EDIT :
Yes sorry .
There's my Controller :
public class HomeController : Controller
{
private static string path = #"C:\LogIngesup\log.xml";
public ActionResult Index()
{
DataTable logs = Write_Log.Read.loadXML(path);
return View(logs);
}
}
There my layout :
<body>
#(Html.Kendo().Splitter()
.Name("vertical")
.Orientation(SplitterOrientation.Vertical)
.Panes(verticalPanes =>
{
verticalPanes.Add()
.HtmlAttributes(new { id = "middle-pane" })
.Scrollable(false)
.Collapsible(false)
.Content(
Html.Kendo().Splitter()
.Name("horizontal")
.HtmlAttributes(new { style = "height: 100%;" })
.Panes(horizontalPanes =>
{
horizontalPanes.Add()
.HtmlAttributes(new { id = "left-pane" })
.Size("230px")
.Resizable(false)
.Collapsible(true)
.Content(#<div>#RenderPage("~/Views/Home/Calendrier.cshtml")</div>);
horizontalPanes.Add()
.HtmlAttributes(new { id = "center-pane" })
.Content(#<div class="pane-content">
<section id="main">
#RenderBody()
</section>
</div>);
horizontalPanes.Add()
.HtmlAttributes(new { id = "right-pane" })
.Collapsible(true)
.Size("220px")
.Content(#<div class="pane-content">
#RenderPage("~/Views/Home/XML.cshtml")
</div>);
}).ToHtmlString()
);
verticalPanes.Add()
.Size("70px")
.HtmlAttributes(new { id = "bottom-pane" })
.Resizable(false)
.Collapsible(true)
.Content(#<div class="pane-content" style="text-align:center">
<p>Application développée par : Dan</p>
</div>);
}))
</body>
And eventually my index.html :
#{
ViewBag.Title = "LogApp";
}
#model System.Data.DataTable
#(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns => {
foreach (System.Data.DataColumn column in Model.Columns)
{
columns.Bound(column.DataType, column.ColumnName);
}
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
)
I'm aware about any suggestion on my code :)
Furthermore I've got an issue :
When I try to add this in my grid (index.html):
.DataSource(datasource=>datasource
.Ajax()
.PageSize(10)
)
.Selectable(selectable => selectable.Mode(GridSelectionMode.Single))
I can't go to other page, and can't select a row ... Can you help me ?
(It works when I write directly the url : localhost\?Grid-page=2)
I had the same problem when putting a Kendo UI Splitter inside a Kendo UI Tabcontrol.
When the Tabcontrol was made before the Splitter it was making this problem, but when I just reversed the order it worked fine.
i.e I changed from:
$(document).ready(function ()
{
$("#ManagementMenu").kendoTabStrip();
$("#splitter").kendoSplitter({
panes: [
{ size: "200px", resizable: false},
{ size: "500px", collapsible: false}
],
});
}
to
$(document).ready(function ()
{
$("#splitter").kendoSplitter({
panes: [
{ size: "200px", resizable: false},
{ size: "500px", collapsible: false}
],
});
$("#ManagementMenu").kendoTabStrip();
}
and the problem was fixed.

Dependency between DropDownList

I have 2 select field in ascx file:
<%=Html.DropDownList("CityID", new SelectList(Model.Cities, "Code", "Name"), new Dictionary<string, object>
{
{"class", "styled"}
})
%>
<%=Html.DropDownList("EstablishmentID", new SelectList(Model.Establishments, "OID", "Name"),
"All Establishment", new Dictionary<string, object>
{
{"class", "styled"}
})
%>
I want that a values of EstablishmentId change when user select new value in CityID.
How can I do this?
Thanks.
PS. ViewEngine is WepPages.
cascading Country and state DDL
#Html.DropDownListFor(model => model.CountryId, Model.CountryList, "--Select Country--", new { #class = "CountryList", style = "width:150px" })
#Html.DropDownListFor(model => model.StateId, Model.StateList, "--Select State--", new { #class = "StateList", style = "width:150px" })
<script type="text/javascript">
$(document).ready(function () {
$.post("/Client/GetModels", { id: $(".CountryList").val() }, function (data) {
populateDropdown($(".StateList"), data);
});
$(".CountryList").change(function () {
$.post("/Client/GetModels", { id: $(this).val() }, function (data) {
populateDropdown($(".StateList"), data);
});
});
});
function populateDropdown(select, data) {
$(".StateList").empty();
$.each(data, function (id, option) {
$(".StateList").append("<option value='" + option.StateId + "'>" + option.State + "</option>");
});
}
</script>
Try this
In view
<div class="popup_textbox_div" style="padding: 0pt;">
<%=Html.DropDownList("CityId", new SelectList(Model.Cities, "Code", "Name", 0), "---Select City---", new { #class = "popup_textbox popup_dropdown valid" })%>
</div>
<div class="popup_textbox_div" style="padding: 0pt;">
<select class="popup_textbox popup_dropdown valid" id="OID" name="Name">
<option>---All Establishment---</option>
</select>
</div>
Add the script
<script type="text/javascript">
$(function () {
$("#CityId").change(function () {
var cityId = $("#CityId").val();
if (!isNaN(cityId) && ( cityId > 0) && ( cityId != null)) {
GetEstablishmentsByAjax(cityId);
}
else {
$("#OID").html("<option value=''>---All Establishment---</option>");
}
});
});
GetEstablishmentsByAjax(cid) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/trail/selectestablishment/" + cid.toString(),
data: "",
dataType: "json",
success: function (data) {
if (data.length > 0) {
var options = "<option value=''> --All Establishment---</option>";
for (s in data) {
var type = data[s];
options += "<option value='" + type.Value + "'>" + type.Text + "</option>";
}
$("#OID").html(options);
}
}
});
}
</script>
In TrailController
public ActionResult selectestablishment(int? id)
{
SelectList establishments = null;
var estb = //put ur code and get list of establishments under selected city
establishments = new SelectList(estb, "OID", "Name");
return Json(establishments, JsonRequestBehavior.AllowGet);
}

Resources