Cannot export hidden columns in Kendo Grid - asp.net-mvc

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;
}
});

Related

checkBox filter table when field is null

I have a table with orders, one of the columns is "Tracking number"
Added a checkbox to so user can choose when to see all orders or just orders without tracking numbers.
here is the checkbox in view :
<div id="TrackingNumber">
<input type="checkbox" name="pos" value=true/>Show All
</div>
the javascript called is :
<script>
$(document).ready(function () {
$.fn.dataTable.ext.search.push(
function (settings, searchData, index, rowData, counter) {
var positions = $('input:checkbox[name="pos"]:checked').map(function () {
return this.value;
}).get();
if (positions.length === 0) {
return true;
}
if (positions.indexOf(searchData[1]) !== -1) {
return true;
}
return false;
}
)
var table = $('#tblData').DataTable();
$('input:checkbox').on('change', function () {
table.draw();
});
});</script>
when checkbox is checked it shows 0 records and when unchecked it shows all.
i want it to show all records when checkbox is checked and show only records WITHOUT tracking numbers
when Unchecked,
Help will be much appreciated :)
Here is a demo:
View:
<table id="tblList" class="table table-striped table-bordered" style="width:100%">
<div>
<input type="checkbox" id="pos" checked="checked"/>Show All
</div>
<thead class="thead-dark">
<tr class="table-info">
<th>pal</th>
<th>via</th>
<th>con</th>
<th>TrackingNumber</th>
</tr>
</thead>
</table>
#section scripts{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$(function () {
var url = "GetAllPakingList";
LoadPack(url);
})
function LoadPack(url) {
$('#tblList').DataTable({
destroy: true,
ajax: {
url: url,
},
columns: [
{ "data": "pal", responsivePriority: 1, "searchable": true },
{ "data": "via", responsivePriority: 2, "searchable": true },
{ "data": "con", responsivePriority: 3, "searchable": true },
{ "data": "trackingNumber", responsivePriority: 4, "searchable": true },
],
});
};
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var trackingNumber = data[3];
if ($('#pos').prop("checked") != true && trackingNumber!="") {
return false;
} else {
return true;
}
}
);
$('input:checkbox').on('change', function () {
var table = $('#tblList').DataTable();
table.draw();
});
</script>
}
ListOutput:
public class ListOutput
{
public string pal { get; set; }
public string via { get; set; }
public string con { get; set; }
public string TrackingNumber { get; set; }
}
result:

Pass webgrid data back to controller via post asp.net mvc

I am new to MVC and would like to know, how to submit whole grid data on submit button click to controller at once using viewmodel.
In View
#model prjMVC4Training.Models.BookViewModel
#{
ViewBag.Title = "Index";
var categories = ViewBag.BookCategories;
var authors = ViewBag.BookAuthors;
var grid = new WebGrid(source: Model.BookData, canSort: true, canPage:true);
}
#using (Html.BeginForm("BookPost", "Book", FormMethod.Post, new { #id = "grid" }))
{
<h2>Book Index Page</h2>
#Html.HiddenFor(m => m.PrimaryKeyID)
#grid.GetHtml(
tableStyle: "table",
alternatingRowStyle: "alternate",
selectedRowStyle: "selected",
headerStyle: "header",
columns: grid.Columns(
grid.Column("Actions",
style: "col1",
canSort: false,
format: #<text>
<button type="button" class="edit-book display-mode" id="#item.BookID">Edit</button>
<button type="button" class="save-book edit-mode" id="#item.BookID">Save</button>
<button type="button" class="cancel-book edit-mode" id="#item.BookID">Cancel</button>
</text>),
grid.Column("BookTitle",
style: "col2",
canSort: true,
format: #<text>
<span id="dBookTitle" class="display-mode">#item.BookTitle</span>
#Html.TextBox("BookData_" + (int)item.BookID + "__BookID", (string)item.BookTitle, new { #class = "edit-mode", size = 45 })
</text>),
grid.Column("AuthorName",
header: "Author",
style: "col3",
canSort: true,
format: #<text>
<span id="dAuthorName" class="display-mode">#item.AuthorName</span>
#Html.DropDownList("AuthorID_" + (int)item.BookID, (ViewBag.BookAuthors as SelectList).Select(option => new SelectListItem
{
Text = option.Text,
Value = option.Value,
Selected = option.Value == #item.AuthorID
}), new { #class = "edit-mode" })
</text>),
grid.Column("CategoryName",
style: "col4",
canSort: true,
format: #<text>
<span id="dCategoryName" class="display-mode">#item.CategoryName</span>
#Html.DropDownList("CategoryID_" + (int)item.BookID, (ViewBag.BookCategories as SelectList).Select(option => new SelectListItem
{
Text = option.Text,
Value = option.Value,
Selected = option.Value == #item.CategoryID
}), new { #class = "edit-mode" })
</text>),
grid.Column("BookISBN",
style: "col5",
format: #<text>
<span id="dBookISBN" class="display-mode">#item.BookISBN</span>
#Html.TextBox("BookISBN_" + (int)item.BookID, (string)item.BookISBN, new { #class = "edit-mode", size = 20 })
</text>),
grid.Column("IsMember",
style: "",
format: #<text>
<span id="dMember" class="display-mode">#item.IsMember</span>
<input type="checkbox" id="MemberID_" + (int)item.BookID name="MemberID" #(item.IsMember == true ? "Checked" : null) class="edit-mode"/>
</text>)))
<button type="submit" value="Save Book Data">Save Book Data</button>
}
On submit button, I want to pass the value to controller
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BookPost(BookViewModel obj)
{
ViewBag.BookCategories = new SelectList(BookHelperData.GetBookCategories(), "CategoryID", "CategoryName", "20");
ViewBag.BookAuthors = new SelectList(BookHelperData.GetAuthors(), "AuthorID", "AuthorName");
//ViewBag.BookAuthors = BookHelperData.GetAuthorsList();
var Book = BookHelperData.GetBooks();
return View(Book);
}
My ViewModel Class is like this-
public class BookViewModel
{
public int PrimaryKeyID { get; set; }
public List<Book> BookData { get; set; }
}
You can write a generic method which loops all the data in grid and transform it to json structure.
function gridTojson() {
var json = '{';
var otArr = [];
var tbl2 = $('#employeeGrid tbody tr').each(function (i) {
if ($(this)[0].rowIndex != 0) {
x = $(this).children();
var itArr = [];
x.each(function () {
if ($(this).children('input').length > 0) {
itArr.push('"' + $(this).children('input').val() + '"');
}
else {
itArr.push('"' + $(this).text() + '"');
}
});
otArr.push('"' + i + '": [' + itArr.join(',') + ']');
}
})
json += otArr.join(",") + '}'
return json;
}
Now on submit button click you need to pass the data to controller.
$('#btnsave').click(function (e) {
//debugger;
var _griddata = gridTojson();
var url = '#Url.Action("UpdateGridData")';
$.ajax({
url: url,
type: 'POST',
data: { gridData: _griddata }
}).done(function (data) {
if (data != "") {
$('#message').html(data);
}
});
});
Now on controller serialize the data back
public ActionResult UpdateGridData(string gridData)
{
var log = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string[]>>(gridData);
return Json("Update Successfully");
}
Here is the post regarding this.

Add Text Search to Kendo Grid

I am trying out the open source Kendo Grid for the first time. I have the basic grid up and running just fine, but now I need to add a search feature, with a search on first and last names. I am trying to do it in ajax but I am stuck on an error:
Error: Cannot call method 'read' of undefined
my code:
<div id="search-index">
<div class="editor-field">
<label>First Name:</label>
#Html.TextBox("FirstName")
<label style = "margin-left: 15px;">Last Name:</label>
#Html.TextBox("LastName", "", new { style = "margin-right: 15px;" })
</div>
<div id="search-controls-index">
<input type="button" id="searchbtn" class="skbutton" value="Search" />
<input type="button" id="addPersonbtn" class="skbutton" value="Add New Person" onclick="location.href='#Url.Action("AddPerson", "Person")'"/>
</div>
</div>
<div id="index-grid"></div>
</div>
$(document).ready(function () {
var grid = $('#index-grid').kendoGrid({
height: 370,
sortable: true,
scrollable: true,
pageable: true,
dataSource: {
pageSize: 8,
transport: {
read: "/Home/GetPeople",
dataType:"json"
}
},
columns: [
{ field: "FirstName", title: "First Name" },
{ field: "LastName", title: "Last Name" },
{ field: "Gender", title: "Gender" },
{ field: "DOB", title: "Date of Birth", template: '#= kendo.toString(new Date(parseInt(DOB.substring(6))), "MM/dd/yyyy") #' },
{ field: "IsStudent", title: "Is a Student?" }]
});
$("#searchbtn").on('click', function () {
var fsname = $("#FirstName").val();
var ltname = $("#LastName").val();
$.ajax({
type: 'GET',
url: '#Url.Content("~/Home/GetPeople")',
data: { fname: fsname, lname: ltname },
success: function (data) {
grid.dataSource.read();
},
error: function () {
$("#index-grid").html("An error occured while trying to retieve your data.");
}
});
});
});
Should matter, but here is my controller (using asp MVC 3):
public JsonResult GetPeople(string fname, string lname)
{
if (((fname == "") && (lname == "")) || ((fname == null) && (lname == null)))
{
var peopleList = repo.GetPeople();
return Json(peopleList, JsonRequestBehavior.AllowGet);
}
else
{
var personResult = repo.GetSearchResult(fname, lname);
return Json(personResult, JsonRequestBehavior.AllowGet);
}
}
The problem is that $("#grid").kendoGrid() returns a jQuery object which doesn't have a dataSource field. Here is how to get a reference to the client-side object: http://docs.kendoui.com/getting-started/web/grid/overview#accessing-an-existing-grid

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