Dynamic grouping mutiple columns aggregation using Dynamic Linq - linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Program
{
static void Main(string[] args)
{
// some sample data
List<AggregateGrouping> lstgrpelements = new List<AggregateGrouping>();
lstgrpelements.Add(new AggregateGrouping{ Name = "Mike", CITY= "Tallahassee", STATE= "FL", value=-3.12M });
lstgrpelements.Add(new AggregateGrouping{ Name = "Mike", CITY= "Tallahassee", STATE= "FL", value=6.57M });
lstgrpelements.Add(new AggregateGrouping{ Name = "Steve", CITY= "Tallahassee", STATE= "FL", value=-7.34M });
lstgrpelements.Add(new AggregateGrouping{ Name = "Steve", CITY= "Tallahassee", STATE= "FL", value=54.64M });
lstgrpelements.Add(new AggregateGrouping{ Name = "Steve", CITY= "Orlando", STATE= "FL", value=-10.93M });
lstgrpelements.Add(new AggregateGrouping{ Name = "Steve", CITY= "Orlando", STATE= "FL", value=235.09M });
lstgrpelements.Add(new AggregateGrouping{ Name = "Mike", CITY= "Orlando", STATE= "NY", value=429.34M });
lstgrpelements.Add(new AggregateGrouping{ Name = "Mike", CITY= "Orlando", STATE= "NY", value=-67.12M });
// Converts to list to iEnumrable.
IEnumerable<AggregateGrouping> enumgrpelements = lstgrpelements;
}
}
Public Class AggregateGrouping
{
public string Name { get; set; }
public string CITY{ get; set; }
public string STATE{ get; set; }
public decimal value{ get; set; }
}
How to have IEnumerable to groupby (CITY AND STATE) dynamic data aggregation (on Values) using Dynamic Linq. CITY AND STATE columns are examples but there can be grouping on multiple columns dynamic at run time. I would like the output as aggregate on Values field.
Thanks, Ashutosh.

A solution is to use my product AdaptiveLINQ. Define a cube by specifying dimensions and measures expressions and combine the use of QueryByCube and Select to compute aggregated values.

Related

Nested objects with Spring Boot, MongoDB

How get nested objects with MongoDb using Spring Boot?
I have 3 DTO, BoardResponse, ColumnsResponse, CardResponse.
public class BoardResponse {
//id, name, createdBy,createdDate,updatedBy,updatedDate, getters
List<ColumnResponse> columns = new ArrayList<ColumnResponse>();
public BoardResponse(KanbanBoard board, List<ColumnResponse> columns) {
super();
this.id = board.getId();
this.name = board.getName();
this.createdBy = board.getCreatedBy();
this.createdDate = board.getCreatedDate();
this.updatedBy = board.getUpdatedBy();
this.updatedDate = board.getUpdatedDate();
this.columns = columns;
}
public class ColumnResponse {
//id, name, createdBy,createdDate,updatedBy,updatedDate, getters
private ObjectId idBoard;
List<CardResponse> cards = new ArrayList<>();
public ColumnResponse(KanbanColumn column, List<CardResponse> cards) {
super();
this.id = column.getId();
this.name = column.getName();
this.createdBy = column.getCreatedBy();
this.createdDate = column.getCreatedDate();
this.updatedBy = column.getUpdatedBy();
this.updatedDate = column.getUpdatedDate();
this.id = column.getIdBoard();
this.idBoard = column.getIdBoard();
this.cards = cards;
}
public class CardResponse {
//id, name, createdBy,createdDate,updatedBy,updatedDate, getters
private ObjectId idColumn;
public CardResponse(KanbanCard card) {
super();
this.id = card.getId();
this.name = card.getName();
this.createdBy = card.getCreatedBy();
this.createdDate = card.getCreatedDate();
this.updatedBy = card.getUpdatedBy();
this.updatedDate = card.getUpdatedDate();
this.idColumn = card.getIdColumn();
}
I want how to do nested with MongoTemplate, I got It using business logic if board exist find by column with board id, if column exist find by card with card id.
I don't know if doing that is a good way.
KanbanBoard, KanbanColumn, is the same as the entity Board and Column, the same properties.
public BoardResponse findBoardById(ObjectId id, UserPrincipal currentUser) {
KanbanBoard board = this.kanbanBoardRepository.findById(id).orElse(null);//find board by id
//find all columns by board ID within the entity #document KanbanColumn
List<KanbanColumn> columns = this.kanbanColumnRepository.findAllByIdBoard(board.getId());
//return list of ColumnResponse DTO
List<ColumnResponse> columnResponse = columns.stream().map(column -> {
return new ColumnResponse(column);
}).collect(Collectors.toList());
//List Column map
List<ColumnResponse> columnMap = new ArrayList<>();
for (ColumnResponse column : columnResponse) {
List<CardResponse> cards = this.kanbanCardRepository.findAllByIdColumn(column.getId()).stream()
.map(card -> new CardResponse(card)).collect(Collectors.toList());
column.setCards(cards); //column set list of cards
columnMap.add(column);//add columns with list of cards inside list of column map
}
//return board with list of column map, with list of cards
return new BoardResponse(board, columnMap);
}
The result is
{
"id": "5e717d6d6e7cbf226074c3fe",
"name": null,
"createdBy": "admin",
"createdDate": 1584495981290,
"updatedBy": "admin",
"updatedDate": 1584495981290,
"columns": [
{
"id": "5e72bfa6cc3ff9000ae93c92",
"name": null,
"createdBy": "admin",
"createdDate": 1584578470269,
"updatedBy": "admin",
"updatedDate": 1584578470269,
"idBoard": null,
"cards": [
{
"id": "5e72de720715f131878b4ed2",
"name": "esse é o card",
"createdBy": "admin",
"createdDate": 1584586354958,
"updatedBy": "admin",
"updatedDate": 1584586354958,
"idColumn": "5e72bfa6cc3ff9000ae93c92"
}
]
},
{
"id": "5e72bfefcc3ff9000ae93c95",
"name": "coluna criada com sucesso.",
"createdBy": "admin",
"createdDate": 1584578543201,
"updatedBy": "admin",
"updatedDate": 1584578543201,
"idBoard": null,
"cards": [
{
"id": "5e72de550715f131878b4ed0",
"name": "esse é o card",
"createdBy": "admin",
"createdDate": 1584586325485,
"updatedBy": "admin",
"updatedDate": 1584586325485,
"idColumn": "5e72bfefcc3ff9000ae93c95"
},
{
"id": "5e72de630715f131878b4ed1",
"name": "esse é o card",
"createdBy": "admin",
"createdDate": 1584586339140,
"updatedBy": "admin",
"updatedDate": 1584586339140,
"idColumn": "5e72bfefcc3ff9000ae93c95"
}
]
}
]
}
The use of MongoTemplate, Aggregation, can be verbose, but the result is the same as MongoRepository.
public BoardResponse findBoardById(ObjectId id, UserPrincipal currentUser) {
//board
AggregationOperation boardId = Aggregation.match(Criteria.where("id").is(id));
Aggregation boardAggregation = Aggregation.newAggregation(boardId);
KanbanBoard boards = mongoTemplate.aggregate(boardAggregation, KanbanBoard.class, KanbanBoard.class)
.getUniqueMappedResult();
//column idBoard equal board ID
AggregationOperation ColumnIdBoardIsLikeBoardId = Aggregation
.match(Criteria.where("idBoard").is(boards.getId()));
Aggregation columnAggregation = Aggregation.newAggregation(ColumnIdBoardIsLikeBoardId);
List<ColumnResponse> listaColumns = mongoTemplate
.aggregate(columnAggregation, KanbanColumn.class, ColumnResponse.class).getMappedResults();
//map every column, column set list of cards
listaColumns.stream().map(column -> {
List<CardResponse> cards =
// find all cards by column ID
this.kanbanCardRepository.findAllByIdColumn(column.getId()).stream()
.map(card -> new CardResponse(card)).collect(Collectors.toList());
column.setCards(cards);
return column;
}).collect(Collectors.toList());
//board DTO set board, list of columns with list of cards
return new BoardResponse(boards, listaColumns);
}

How do I filter a list of objects with linq with multiple criteria?

I am trying to filter a list of objects by multiple criteria. First of all, if the Name and Code are the same for two or more records, I only want to return one. However, if the Status of one is "suspended" and the Status of the second is "rented", I only want to return the record with "suspended" status. This is what I've got so far:
public class Customer
{
public string UnitName { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Status { get; set; }
}
public static IEnumerable<Customer> FilterDuplicates(IEnumerable<Customer> customers)
{
return customers
.GroupBy(c => new {c.Name, c.Code})
.Select(g => g.First());
}
For example, the following data should return Mister Twister, Frank Furter and the record where the status is "suspended" for Jane Jones:
{
"unitName": "A22",
"code": "00122",
"status": "rented",
"phone": "2125551212",
"name": "Jones, Jane"
},
{
"unitName": "A07",
"code": "00122",
"status": "suspended",
"phone": "2125551212",
"name": "Jones, Jane"
},
{
"unitName": "C19",
"code": "00222",
"status": "suspended",
"phone": "2125557777",
"name": "Furter, Frank"
},
{
"unitName": "B14",
"code": "00333",
"status": "rented",
"phone": "2125559999",
"name": "Twister, Mister"
}
You should order the contents of each group and then you can select which one you want:
return customers
.GroupBy(c => new {c.Name, c.Code})
.Select(g => g.OrderByDescending(c => c.status).First());
NOTE: This is essentially a particular implementation of DistinctBy, which in full general form I implement with:
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> src, Func<T, TKey> keySelector, Func<IGrouping<TKey, T>, T> pickFn, IEqualityComparer<TKey> comparer = null) =>
src.GroupBy(keySelector, comparer).Select(pickFn);
Which you could then use as
return customers.DistinctBy(c => new { c.Name, c.Code }),
g => g.OrderByDescending(c => c.status).First());

MongoDB search nested objects in an array

I am using MongoDB to store all the events in my Eventbrite clone. So I have a collection called events then the objects in this collection consists of their name and and array of users that have rsvp to the event. I can query for any events that the current user has created but unable to figure out how to query both events the user has created and rsvp to.
Here is the compiled query that I am using to try to get all the users events.
events.find({"$and":[{"user_id":"5d335704802df000076bad97"},{"user_id":{"$ne":null}}],"$or":[{"checkins.user_id":"5d335704802df000076bad97"}]},{"typeMap":{"root":"array","document":"array"}})
I am using the Laravel MongoDB plugin to query my data in php it looks like this
$user->events()->orWhere(function ($query) use ($user){
return $query->where('checkins.user_id',new ObjectID($user->id));
})->get()
The event object looks something like this:
{
"name": "test",
"user_id": "1"
"rsvp": [
{"user_id": "12"}
]
}
An user can rsvp to other event that are not their own.
you need an $or filter and $elemMatch to get events that belong to a given user or events they've rsvp'd to.
db.events.find({
"$or": [
{
"user_id": "5d33e732e1ea9d0d6834ef3d"
},
{
"rsvp": {
"$elemMatch": {
"user_id": "5d33e732e1ea9d0d6834ef3d"
}
}
}
]
})
unfortunately i can't help you with laravel version of the query. in case it helps, below is the c# code that generated the above mongo query.
using MongoDB.Entities;
using System.Linq;
namespace StackOverflow
{
public class Program
{
public class user : Entity
{
public string name { get; set; }
}
public class Event : Entity
{
public string name { get; set; }
public string user_id { get; set; }
public rsvp[] rsvp { get; set; }
}
public class rsvp
{
public string user_id { get; set; }
}
private static void Main(string[] args)
{
new DB("test");
var mike = new user { name = "mike" };
var dave = new user { name = "dave" };
mike.Save();
dave.Save();
(new[] {
new Event
{
name = "mike's event",
user_id = mike.ID,
rsvp = new[]
{
new rsvp { user_id = dave.ID }
}
},
new Event
{
name = "dave's event",
user_id = dave.ID,
rsvp = new[]
{
new rsvp { user_id = mike.ID }
}
}
}).Save();
var result = DB.Find<Event>()
.Many(e =>
e.user_id == mike.ID ||
e.rsvp.Any(r => r.user_id == mike.ID));
}
}
}

Problems with MVC 3 DropDownList() in WebGrid()

I'm trying to place a DropDownList inside a WebGrid but I can't figure out how to do it :(
Things I've tried:
grid.Column("Id", "Value", format: ((item) =>
Html.DropDownListFor(item.SelectedValue, item.Colors)))
and
grid.Column(header: "", format: (item => Html.DropDownList("Colors", item.Colors)))
and
grid.Column(header: "", format: Html.DropDownList("Colors"))
and various others but I couldn't get it to work.
Any help is much appreciated.
Model
public class PersonViewModel
{
public string Name { get; set; }
public int Age { get; set; }
public SelectList Colors { get; set; }
public int SelectedValue { get; set; }
}
public class ColorViewModel
{
public int ColorID { get; set; }
public string ColorName { get; set; }
}
Controller
public ActionResult Index()
{
var colorList = new List<ColorViewModel>() {
new ColorViewModel() { ColorID = 1, ColorName = "Green" },
new ColorViewModel() { ColorID = 2, ColorName = "Red" },
new ColorViewModel() { ColorID = 3, ColorName = "Yellow" }
};
var people = new List<PersonViewModel>()
{
new PersonViewModel() {
Name = "Foo",
Age = 42,
Colors = new SelectList(colorList)
},
new PersonViewModel() {
Name = "Bar",
Age = 1337,
Colors = new SelectList(colorList)
}
};
return View(people);
}
View
#model IEnumerable<PersonViewModel>
#{
var grid = new WebGrid(Model);
}
<h2>DropDownList in WebGrid</h2>
#using (Html.BeginForm())
{
#grid.GetHtml(
columns: grid.Columns(
grid.Column("Name"),
grid.Column("Age"),
grid.Column() // HELP - INSERT DROPDOWNLIST
)
)
<p>
<button>Submit</button>
</p>
}
grid.Column(
"dropdown",
format: #<span>#Html.DropDownList("Color", (SelectList)item.Colors)</span>
)
Also in your controller make sure you set the value and text properties of your SelectList and instead of:
Colors = new SelectList(colorList)
you should use:
Colors = new SelectList(colorList, "ColorID", "ColorName")
Also it seems a bit wasteful to me to define the same SelectList for all row items especially if they contain the same values. I would refactor your view models a bit:
public class MyViewModel
{
public IEnumerable<SelectListItem> Colors { get; set; }
public IEnumerable<PersonViewModel> People { get; set; }
}
public class PersonViewModel
{
public string Name { get; set; }
public int Age { get; set; }
public int SelectedValue { get; set; }
}
and then:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// define the values used to render the dropdown lists
// for each row
Colors = new[]
{
new SelectListItem { Value = "1", Text = "Green" },
new SelectListItem { Value = "2", Text = "Red" },
new SelectListItem { Value = "3", Text = "Yellow" },
},
// this is the collection we will be binding the WebGrid to
People = new[]
{
new PersonViewModel { Name = "Foo", Age = 42 },
new PersonViewModel { Name = "Bar", Age = 1337 },
}
};
return View(model);
}
}
and in the view:
#model MyViewModel
#{
var grid = new WebGrid(Model.People);
}
<h2>DropDownList in WebGrid</h2>
#using (Html.BeginForm())
{
#grid.GetHtml(
columns: grid.Columns(
grid.Column("Name"),
grid.Column("Age"),
grid.Column(
"dropdown",
format: #<span>#Html.DropDownList("Color", Model.Colors)</span>
)
)
)
<p>
<button>Submit</button>
</p>
}
UPDATE:
And since I suspect that you are not putting those dropdownlists for painting and fun in your views but you expect the user to select values inside them and when he submits the form you might wish to fetch the selected values, you will need to generate proper names of those dropdown lists so that the default model binder can automatically retrieve the selected values in your POST action. Unfortunately since the WebGrid helper kinda sucks and doesn't allow you to retrieve the current row index, you could use a hack as the Haacked showed in his blog post:
grid.Column(
"dropdown",
format:
#<span>
#{ var index = Guid.NewGuid().ToString(); }
#Html.Hidden("People.Index", index)
#Html.DropDownList("People[" + index + "].SelectedValue", Model.Colors)
</span>
)
Now you could have a POST controller action in which you will fetch the selected value for each row when the form is submitted:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// the model variable will contain the People collection
// automatically bound for each row containing the selected value
...
}
..make my dropdown list to select a value from the list when it loads.The following works for sure. I have tried it out myself. Any questions keep me posted.
#Html.DropDownList("RejectReason", Model.SalesReasonList.Select(u => new SelectListItem
{
Text = u.Text,
Value = u.Value,
Selected = u.Value ==#item.RejectReason
}))

Populating child drop down based on what was selected from parent drop down list

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

Resources