I trying to implement a cascading down list with editor template i am not sure if kendo support it, i have a grid when in editing move i am trying to filter data base on select data from an editor template
grid is showing availablity time a user can work
e.g column Timefrom, TimeTo, status, could be the following
1.) availablity
2.) Unavailablity
3.) Holiday
availablity have different time template compare to Holiday and unavailablity
e.g
"Early/day" - 07.00 -18.00
"Long day" - 0700 - 22.30
"Late" - 12.00 - 22.00
"Night" - 19.00 - 21.00
"Twilight" - 18.00 - 04.00
Holiday/Unavailablity - half day morning
holiday/Unavailablity - half day afternoon
holiday/Unavailablity - evening
holiday/Unavailablity - whole day
what i want to achive when user click on edit mode, status column have a drop down with [Availablity - Unavilablity - Holiday ] after selecting the option availablity time template will be enable with the respective time template.
example when user click on Holiday drop down in edit mode only these option should be display on availablity Time Template column ("Early/day","Long day","Late","Night","Twilight")
below is a demo code simmilar concept to the main application Thanks
main page
#(Html.Kendo().Grid<Availablity>()
.Name("grid-availablity")
.Columns(columns =>
{
columns.Bound(c => c.Id);
columns.Bound(c => c.TimeFrom);
columns.Bound(c => c.TimeTo);
columns.Bound(c => c.Status);
columns.Bound(c => c.AvailablityTimeTemplate); // only testing purpose
columns.Command(command =>
{
command.Edit();
});
})
.DataSource(databinding => databinding.Ajax().PageSize(10).ServerOperation(false)
.Model(model => model.Id(availablity => availablity.Id))
.Read("GetAvailablityList","Availability")
.Update("Availablity_Update","Availability")
)
)
<script>
function filterTimeTemplate() {
return {
AvailablityTimeTemplate: $("#AvailablityTimeTemplate").val()
};
}
</script>
Editor Template
Status Template
#(Html.Kendo().DropDownList()
.Name("Status")
//.DataTextField("")
//.DataValueField("Id")
.OptionLabel("Change Status")
.BindTo(Enum.GetNames(typeof(Status)).ToList())
)
Time Template
#(Html.Kendo().DropDownList()
.Name("AvailablityTimeTemplate")
.HtmlAttributes(new { style = "width:300px" })
.OptionLabel("Change Time...")
//.DataTextField("")
// .DataValueField("")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCascadingData", "Availability")
.Data("filterTimeTemplate");
})
.ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
.CascadeFrom("Status")
)
classes and enum
public class Availablity
{
public string Id { get; set; }
public string TimeFrom { get; set; }
public string TimeTo { get; set; }
[UIHint("AvailablityStatus")]
public Status Status { get; set; }
[UIHint("TimeTemplate")]
public string AvailablityTimeTemplate { get; set; }
public List<Availablity> GetAvailablity()
{
return new List<Availablity>()
{
new Availablity(){ Id="001", TimeFrom="0700", TimeTo="18.00", Status=Status.Available},
new Availablity(){ Id="002", TimeFrom="0700", TimeTo="23.30", Status=Status.Available},
new Availablity(){ Id="002", TimeFrom="12.00", TimeTo="22.00", Status=Status.Available}
};
}
public List<string> GetTimeTemplateList(Status status)
{
List<string> TimeTemplateCollection = null;
if (status == Status.Available) {
TimeTemplateCollection = new List<string>(){
"Long day","Late","Night","Twilight"
};
} else {
TimeTemplateCollection = new List<string>(){
"Morning Half Day","Afternoon - Half Day ","Night","Whole Day"
};
}
return TimeTemplateCollection;
}
}
public enum Status
{
Available = 0,
UnAvailable = 1,
Holiday = 2
}
controller
public JsonResult GetCascadingData(Status availablityStatus)
{
var availablity = new Availablity();
var data = availablity.GetTimeTemplateList(availablityStatus);
return Json(data, JsonRequestBehavior.AllowGet);
}
public JsonResult GetAvailablityList([DataSourceRequest] DataSourceRequest request)
{
var availablity = new Availablity();
var data = availablity.GetAvailablity();
return Json(data.AsQueryable().ToDataSourceResult(request));
}
As your comment explain further, this is what you need to change
Time Template
#(Html.Kendo().DropDownList()
.Name("AvailablityTimeTemplate")
.HtmlAttributes(new { style = "width:300px" })
.OptionLabel("Change Time...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCascadingData", "Availability").Data("filterTimeTemplate");
})
.ServerFiltering(true);
})
//.Enable(false) should be removed
.AutoBind(false)
.CascadeFrom("Status")
)
Related
Kendo drop down is empty for some reason and I am not sure, below is all my code
#(Html.Kendo().DropDownList()
.Name("parties")
.HtmlAttributes(new { style = "width: 250px" })
.DataTextField("Name")
.DataValueField("PartyId")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetParties", "Concept");
});
})
)
Controller Call
public JsonResult GetParties([DataSourceRequest] DataSourceRequest request)
{
var parties = MiscAdapter.GetParties().Select(x => new PartyModel
{
Name = x.PartyName,
PartyId = x.PartyId
});
return Json(parties.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
Model
public class PartyModel
{
public int PartyId { get; set; }
public string Name { get; set; }
}
Data returned according to the F12 tools
{"Data":[{"PartyId":1,"Name":"New Democratic Party"},{"PartyId":2,"Name":"Saskatchewan Party"},{"PartyId":3,"Name":"Liberal"},{"PartyId":4,"Name":"Green"},{"PartyId":5,"Name":"Independant"}],"Total":5,"AggregateResults":null,"Errors":null}
The dropdown does not show anything in there even though i cant see anything with the code or returned data.
Please try with the below code snippet. The method you have used its used for grid data binding.
public JsonResult GetParties()
{
List<PartyModel> models = new List<PartyModel>();
models.Add(new PartyModel() { Name = "Name1", PartyId = 1 });
models.Add(new PartyModel() { Name = "Name2", PartyId = 2 });
return Json(models, JsonRequestBehavior.AllowGet);
}
Let me know if any concern.
I'm using Kendo UI 2013.2.716, specifically KendoGrid, C#, Visual Studio 2010, I need to change the globalization of the message "The field X must be a number." as seen in the image and put it in another language.
If I inspect the element in Chrome I see:
I tried doing this:
ViewModel
namespace Test.Models
{
public class TestModel
{
...
[DisplayName("Pos")]
[IsNumberAttribute(ErrorMessage = "Ingrese un número.")]
public int Pos { get; set; }
}
}
namespace Test.Models.CustomValidator
{
[AttributeUsage(AttributeTargets.Property)]
public class IsNumberAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
try
{
int numeroTemp;
bool esNumero = int.TryParse((string)value, out numeroTemp);
return esNumero;
}
catch (Exception)
{
return base.IsValid(value);
}
}
}
}
But it did not work, still in English :(
In my View I have this:
#(Html.Kendo().Grid<Test.Models.TestModel>(Model)
.Name("titulo")
.Columns(columns =>
{
...
columns.Bound("Pos").Filterable(false);
columns.Bound("Edad").Title("Edad").ClientTemplate("#=window.TestMantenedor.Valida(edad)#").Width(500);
})
.ToolBar(toolbar =>
{
toolbar.Create().Text("Agregar");
toolbar.Save().SaveText("Modificar").CancelText("Cancelar");
})
.Editable(editable =>
{
editable.DisplayDeleteConfirmation(false);
editable.Mode(GridEditMode.InCell);
})
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Batch(true)
.Model(model =>
{
...
model.Field(p => p.Edad).DefaultValue(true);
})
.Create("Create", "Test", new { id = id })
.Events(events => events.Error("error_handler"))
.Events(events => events.RequestEnd("success_handler"))
)
.Filterable(filterable => filterable.Messages(messages =>
{
messages.Info("Mostrar plantillas en estado");
messages.Filter("Filtrar");
messages.Clear("Borrar");
messages.IsTrue("Valido");
messages.IsFalse("No valido");
})
)
.Pageable(p => p
.Messages(m => m
.Display("Mostrando {0}-{1} de {2} registros")
.Empty("No se encontraron registros")
.First("Ir a la primera página")
.Last("Ir a la última página")
.Next("Ir a la página siguiente")
.Previous("Ir a la página anterior")
)
)
)
Any help?
Finally, after 3 days trying a lot of stuff, also try the solutions of
How to change 'data-val-number' message validation in MVC while it is generated by #Html helper
#(Html.Kendo().Grid<Test.TestModel>(Model)
.Name("listado")
.Columns(columns =>
{
columns.Bound("idElementColumn").Filterable(false);
...
}
And at least, in the end of View I put:
<script type="text/javascript">
$("#listado").on("click", function (e) {
$(".k-grid #idElementColumn").attr('data-val-number', 'Ingrese un número.');
});
</script>
I am facing an issue with Kendo grid inline editing, The issue is even though I update any row, 1st row data is displayed in grid, Any help on this?
Before update
After update.
Interestingly the object I return from the controller does have the correct data
Controller code
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
[ActionSessionState(System.Web.SessionState.SessionStateBehavior.Required)]
[OutputCache(Duration = 0, VaryByParam = "none")]
public ActionResult _SaveBatchEditingintegrate([DataSourceRequest] DataSourceRequest request)
{
var UPObj = SessionFacade.UserProfile as UserProfile;
try
{
IntegrationRate objInteg = new IntegrationRate();
TryUpdateModel(objInteg);
if (objInteg.PeriodID != 0)
{
var Integrationrate = (from p in _draftManagecompany.IntegrationRates where p.PeriodID == objInteg.PeriodID select p).First();
TryUpdateModel(Integrationrate);
if (Integrationrate.Rate > 100) //set 100 as default
{
Integrationrate.Rate = 100;
}
}
LoadResourceJSArray();
}
catch (Exception ex)
{
// Adding related additional information along with exception object
//ExceptionLogger.Log(ex, "Period ID", id);
ExceptionLogger.Log(ex, "User Profile Info", UPObj);
// Handle exception with BubbleExceptionPolicy
if (exManager.HandleException(ex, "BubbleExceptionPolicy"))
throw; // Not to include the ex, as the previous stack trace to be maintained
}
//_draftManagecompany.IntegrationRates contains updated value in the correct order
return Json(_draftManagecompany.IntegrationRates.ToDataSourceResult(request));
}
cshtml code:
#{ var integrateGrid = Html.Kendo()
.Grid(Model.Company.IntegrationRates)
.Name("Gridintegrate")
.EnableCustomBinding(true) // Enable custom binding
.BindTo(Model.Company.IntegrationRates)
.Events(events =>
{
events.Change("DataBound_Integ");
})
.ToolBar(
commands =>
{
//commands.Insert().ButtonType(GridButtonType.BareImage).ImageHtmlAttributes(new { style = "visibility:hidden" });
}
)
.Columns(columns =>
{
columns.Bound(p => p.PeriodID).Visible(false);
columns.Bound(p => p.Month).Width(150);
columns.Bound(p => p.Rate).Format("{0:0.00}%").Width(100);
columns.Command(commands =>
{
commands.Edit().HtmlAttributes(new { #id = "btn_IntRateEdit" });
}).Width(150).Title(gridTitle);
})
.HtmlAttributes(new { style = "height: 380px;" })
.Scrollable()
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource.Ajax()
//.Batch(true)
.Read(read => read.Action("_AjaxBindingintegrate", "Company"))
.Update(update => update.Action("_SaveBatchEditingintegrate", "Company"))
.Model(model =>
{
model.Id(c => c.PeriodID);
model.Field(c => c.Month).Editable(false);
}
)
.Events(events =>
{
events.Error("CheckSessionExistsOnTelerik");
})
);
//.Pageable(paging => paging.Style(GridPagerStyles.NextPreviousAndNumeric | GridPagerStyles.PageSizeDropDown).PageSize(20, new int[3] { 20, 50, 100 })).ToComponent();
var culture = System.Globalization.CultureInfo.InvariantCulture;
//integrateGrid.Localization = new GridControlLocalization(culture);
integrateGrid.Render();
}
I think I see the problem here. From what I can tell when you complete the update you are returning the entire data set back on the update ie June, january, February etc.
On the update all you have to do is return the item you have updated back to the grid
So in your example change the return json to the following:
Return json(new { IntegrationRate}.toDataSourceResult(request,modelState),jsonbehaviour.allowget);
This then should sort out your issue.
Because you are returning the entire data set back it is rendering the first row as the expected result.
As you say you see the data saving correctly behind the scenes. So you know an error is not being thrown.
I am writing an ASP.NET MVC4 / Razor / C# based application that needs to render a grid of records. Each row has several columns, and there may be 100 or so rows.
Each row has a checkbox field, text field and then three cascading dropdown lists. The first dropdown is prepopulated on page load. The second needs to be populated using Ajax on change of the first dropdown list. The third from a change on the second. Each row is separate and does not influence each other.
What is the recommended way to implement something like this? The various solutions for cascading dropdown lists are only for single cascading lists - they do not work (for me) when placed inside a foreach loop.
The skeleton of what I have is shown below:
#model IList<MyModel>
#using (Html.BeginForm("MyAction", "Home")) {
<table><tr><th>Use?</th><th>Name</th><th>List A</th><th>List B</th><th>List C</th></tr>
#Html.EditorForModel()
</table>
}
The model looks something like this:
public class MyModel
{
public bool Use { get; set; }
public string Name { get; set; }
public int? ListAId { get; set; }
public int? ListBId { get; set; }
public int? ListCId { get; set; }
public IList<ListAList> ListA { get; set; }
}
The shared EditorTemplates file MyModel.cshtml follows this structure:
#model MyNamespace.MyModel
<tr>
<td>#Html.CheckBoxFor(model => model.Use)</td>
<td>#Html.DisplayFor(model => model.Name)</td>
<td>#Html.DropDownListFor(model => model.ListAId, new SelectList(Model.ListA, "Id", "Name", Model.ListAId), "")</td>
<td>??</td>
<td>??</td>
</tr>
The ?? indicates I am unsure what to put in here.
How do I proceed to render the ListB select box using Ajax on change of the ListA select box, then on change of ListB render the ListC select box?
check this:
on select change event - Html.DropDownListFor
http://addinit.com/node/19
or
http://www.codeproject.com/Articles/258172/Simple-Implementation-of-MVC-Cascading-Ajax-Drop-D
Update1: Suppose that there is Name ROWID, (and list all the same data source).
Update2: the example available on github
Based on these responses:
How to populate a #html.dropdownlist mvc helper using JSon
Populate a <select></select> box with another
Model:
using System.Collections.Generic;
namespace MyNamespace
{
public class MyModel
{
public MyModel() { ListA = new List<ListAList>(); }
public bool Use { get; set; }
public string Name { get; set; }
public int? ListAId { get; set; }
public int? ListBId { get; set; }
public int? ListCId { get; set; }
public IList<ListAList> ListA { get; set; }
}
public class ListAList
{
public int Id { get; set; }
public string Name { get; set; }
}
}
Main action in the Home Controller:
public ViewResult MyAction()
{
var model = new List<MyModel>();
for (int i = 0; i < 10; i++)
{
var item = new MyModel()
{
Name = string.Format("Name{0}", i),
Use = (i % 2 == 0),
ListAId = null,
ListBId = null,
ListCId = null
};
for (int j = 0; j < 10; j++)
{
item.ListA.Add( new ListAList()
{
Id=j,
Name = string.Format("Name {0}-{1}",i,j)
});
}
model.Add(item);
}
return View(model);
}
Data source provider in the Home controller:
public JsonResult PopulateOption(int? listid, string name)
{
//todo: preparing the data source filter
var sites = new[]
{
new { id = "1", name = "Name 1" },
new { id = "2", name = "Name 2" },
new { id = "3", name = "Name 3" },
};
return Json(sites, JsonRequestBehavior.AllowGet);
}
EditorTemplate:
#model MyNamespace.MyModel
<tr>
<td>#Html.CheckBoxFor(model => model.Use)</td>
<td>#Html.DisplayFor(model => model.Name)</td>
<td>#Html.DropDownListFor(model => model.ListAId, new SelectList(Model.ListA, "Id", "Name", Model.ListAId), "", new { #id = string.Format("ListA{0}", Model.Name), #class="ajaxlistA" })</td>
<td><select class="ajaxlistB" id="ListB#(Model.Name)"></select></td>
<td><select class="ajaxlistC" id="ListC#(Model.Name)"></select></td>
</tr>
And the main view with Ajax functions:
#using MyNamespace
#model IList<MyModel>
#using (Html.BeginForm("MyAction", "Home")) {
<table><tr><th>Use?</th><th>Name</th><th>List A</th><th>List B</th><th>List C</th></tr>
#Html.EditorForModel()
</table>
}
<script src="#Url.Content("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></script>
<script>
$(document).ready( $(function () {
$('.ajaxlistA').change(function () {
// when the value of the first select changes trigger an ajax request
list = $(this);
var listvalue = list.val();
var listname = list.attr('id');
$.getJSON('#Url.Action("PopulateOption", "Home")', { listid: listvalue, name: listname }, function (result) {
// assuming the server returned json update the contents of the
// second selectbox
var listB = $('#' + listname).parent().parent().find('.ajaxlistB');
listB.empty();
$.each(result, function (index, item) {
listB.append(
$('<option/>', {
value: item.id,
text: item.name
})
);
});
});
});
$('.ajaxlistB').change(function () {
// when the value of the first select changes trigger an ajax request
list = $(this);
var listvalue = list.val();
var listname = list.attr('id');
$.getJSON('#Url.Action("PopulateOption", "Home")', { listid: listvalue, name: listname }, function (result) {
// assuming the server returned json update the contents of the
// second selectbox
var listB = $('#' + listname).parent().parent().find('.ajaxlistC');
listB.empty();
$.each(result, function (index, item) {
listB.append(
$('<option/>', {
value: item.id,
text: item.name
})
);
});
});
});
}));
</script>
And the result:
I am using the latest version of jQuery and ASP.NET MVC 3 with the Razor view engine.
I have tried Google looking for a decent example of loading a child drop down list when a parent drop down item is selected. I am looking to do this via jQuery AJAX using JSON. My knowledge of this is zero.
I have a Category class with a list of categories. It's a parent-child association.
If I select a category from the parent drop down list, then all the child categories need to be listed in the child drop down list for the selected parent category.
This is what I currently have, but need to complete it, not sure if I am in the right direction:
$(document).ready(function () {
$('#ddlParentCategories').change(function () {
alert('changed');
});
});
I loaded my drop down list from my view model as such:
#Html.DropDownListFor(x => x.ParentCategoryId, new SelectList(Model.ParentCategories, "Id", "Name", Model.ParentCategoryId), "-- Select --", new { id = "ddlParentCategories" })
The first item has text "-- Select --" (for both parent and child drop down lists). On initial page load nothing must be loaded in the child drop down list. When a value is selected then the child drop down list must be populated. And when "-- Select --" is selected again in the parent drop down list then all the items in the child drop down list must cleared except "-- Select --".
If possible, if the child categories is loading, how do I display that "round" loading icon?
UPDATE
I have updated my code to Darin's code, and I cannot get it to work properly:
Category class:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public bool IsActive { get; set; }
public int? ParentCategoryId { get; set; }
public virtual Category ParentCategory { get; set; }
public virtual ICollection<Category> ChildCategories { get; set; }
}
EditProductViewModel class:
public class EditProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string ShortDescription { get; set; }
public string LongDescription { get; set; }
public bool IsActive { get; set; }
public string PageTitle { get; set; }
public bool OverridePageTitle { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public int ParentCategoryId { get; set; }
public IEnumerable<Category> ParentCategories { get; set; }
public int ChildCategoryId { get; set; }
public IEnumerable<Category> ChildCategories { get; set; }
}
ProductController class:
public ActionResult Create()
{
EditProductViewModel viewModel = new EditProductViewModel
{
ParentCategories = categoryService.GetParentCategories()
.Where(x => x.IsActive)
.OrderBy(x => x.Name),
ChildCategories = Enumerable.Empty<Category>(),
IsActive = true
};
return View(viewModel);
}
public ActionResult AjaxBindingChildCategories(int parentCategoryId)
{
IEnumerable<Category> childCategoryList = categoryService.GetChildCategoriesByParentCategoryId(parentCategoryId);
return Json(childCategoryList, JsonRequestBehavior.AllowGet);
}
Create view:
<tr>
<td><label>Parent Category:</label> <span class="red">*</span></td>
<td>#Html.DropDownListFor(x => x.ParentCategoryId,
new SelectList(Model.ParentCategories, "Id", "Name", Model.ParentCategoryId),
"-- Select --",
new { data_url = Url.Action("AjaxBindingChildCategories"), id = "ParentCategories" }
)
#Html.ValidationMessageFor(x => x.ParentCategoryId)
</td>
</tr>
<tr>
<td><label>Child Category:</label> <span class="red">*</span></td>
<td>#Html.DropDownListFor(x => x.ChildCategoryId,
new SelectList(Model.ChildCategories, "Id", "Name", Model.ChildCategoryId),
"-- Select --",
new { id = "ChildCategories" }
)
#Html.ValidationMessageFor(x => x.ChildCategoryId)
</td>
</tr>
<script type="text/javascript">
$(document).ready(function () {
$('#ParentCategories').change(function () {
var url = $(this).data('url');
var data = { parentCategoryId: $(this).val() };
$.getJSON(url, data, function (childCategories) {
var childCategoriesDdl = $('#ChildCategories');
childCategoriesDdl.empty();
$.each(childCategories, function (index, childCategory) {
childCategoriesDdl.append($('<option/>', {
value: childCategory, text: childCategory
}));
});
});
});
});
</script>
It goes into my AjaxBindingChildCategories action and it brings back records, it just doesn't want to display my child category dropdownlist. I had a look in Fire Bug and the error that I get is:
GET AjaxBindingChildCategories?parentCategoryId=1
500 Internal Server Error
Here's an example of cascading drop down lists. As always start by defining a view model:
public class MyViewModel
{
[DisplayName("Country")]
[Required]
public string CountryCode { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
public string City { get; set; }
public IEnumerable<SelectListItem> Cities { get; set; }
}
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// TODO: Fetch countries from somewhere
Countries = new[]
{
new SelectListItem { Value = "FR", Text = "France" },
new SelectListItem { Value = "US", Text = "USA" },
},
// initially we set the cities ddl to empty
Cities = Enumerable.Empty<SelectListItem>()
};
return View(model);
}
public ActionResult Cities(string countryCode)
{
// TODO: based on the selected country return the cities:
var cities = new[]
{
"Paris", "Marseille", "Lyon"
};
return Json(cities, JsonRequestBehavior.AllowGet);
}
}
a view:
#model MyViewModel
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(x => x.CountryCode)
#Html.DropDownListFor(
x => x.CountryCode,
Model.Countries,
"-- Select country --",
new { data_url = Url.Action("cities") }
)
#Html.ValidationMessageFor(x => x.CountryCode)
</div>
<div>
#Html.LabelFor(x => x.City)
#Html.DropDownListFor(
x => x.City,
Model.Cities,
"-- Select city --"
)
#Html.ValidationMessageFor(x => x.City)
</div>
<p><input type="submit" value="OK" /></p>
}
and finally the unobtrusive javascript in a separate file:
$(function () {
$('#CountryCode').change(function () {
var url = $(this).data('url');
var data = { countryCode: $(this).val() };
$.getJSON(url, data, function (cities) {
var citiesDdl = $('#City');
citiesDdl.empty();
$.each(cities, function (index, city) {
citiesDdl.append($('<option/>', {
value: city,
text: city
}));
});
});
});
});
jQuery script will look like this:
<script type="text/javascript">
function getCities(abbr) {
$.ajax({
url: "#Url.Action("Cities", "Locations")",
data: {abbreviation: abbr},
dataType: "json",
type: "POST",
error: function() {
alert("An error occurred.");
},
success: function(data) {
var items = "";
$.each(data, function(i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$("#City").html(items);
}
});
}
$(document).ready(function(){
$("#State").change(function() {
var abbr = $("#State").val();
getCities(abbr);
});
});
</script>
A repository to retrieve data could look like this (obviously hook it up to live data though):
public class LocationRepository : ILocationRepository
{
public IQueryable<State> GetStates()
{
return new List<State>
{
new State { Abbreviation = "NE", Name = "Nebraska" },
new State { Abbreviation = "NC", Name = "North Carolina" }
}.AsQueryable();
}
public IQueryable<City> GetCities(string abbreviation)
{
var cities = new List<City>();
if (abbreviation == "NE")
{
cities.AddRange(new List<City> {
new City { Id = 1, Name = "Omaha" },
new City { Id = 2, Name = "Lincoln" }
});
}
else if (abbreviation == "NC")
{
cities.AddRange(new List<City> {
new City { Id = 3, Name = "Charlotte" },
new City { Id = 4, Name = "Raleigh" }
});
}
return cities.AsQueryable();
}
}
public interface ILocationRepository
{
IQueryable<State> GetStates();
IQueryable<City> GetCities(string abbreviation);
}
Controllers could look like this:
public class LocationsController : Controller
{
private ILocationRepository locationRepository = new LocationRepository();
[HttpPost]
public ActionResult States()
{
var states = locationRepository.GetStates();
return Json(new SelectList(state, "Id", "Name"));
}
[HttpPost]
public ActionResult Cities(string abbreviation)
{
var cities = locationRepository.GetCities(abbreviation);
return Json(new SelectList(cities, "Abbreviation", "Name"));
}
}
I am assuming you populate the parent dropdown from server side and also the first option in this parent dd is "--- Select ---"
You can try this
$(document).ready(function () {
var $parent = $('#ddlParentCategories');
var $child = $('#ddlChildCategories');
$child.find("option:gt(0)").remove();
if(!$parent.children().eq(0).is(":selected")){
$parent.change(function () {
$.ajax({
url: "urlToFetchTheChild",
data: { categoryId: this.value },
success: function(data){
//The data you send should be a well formed array of json object containing code/value pair of child categories
for(var i = 0;i<data.length;i++){
$child.append("<option value='"+ data[i].code +"'>"+ data[i].value +"</option>");
}
}
});
});
}
});