Linq for Javascript / jQuery

I recently started writing a webpage where I wanted some information pre-loaded, without the delay of making an ajax call! What I had was the classic case of the content of one drop down list being controlled by another drop down list.

So, in my controller I loaded up all the data into my model …

public class MyController : Controller
    private readonly IMyRepository _myRepository;

    public MyController(IMyRepository myRepository)
        _myRepository = myRepository;

    public ActionResult MyAction()
        var parentList = _myRepository
            .Select(x => new SelectListItem
                Value = x.ID.ToString(),
                Text = x.Description,
                Selected = false

        var childList = _myRepository

        var model = new MyViewModel
            ParentList = parentList,
            ChildList = childList

    return View(model);

The GetChildList() method returns a list of items which have a ParentID

This is what my view looks like …

@model MyViewModel

<div class="MyViewClass">
    <h2>Parent/Child Example using jQuery Linq</h2>

    <label for="ParentList">Parent Item</label>
    @Html.DropDownListFor(model => model.ParentList, null, "Please select a Parent item ...", new { @class = "test" })

    <label for="ChildList">Child Item</label>
    <select id="ChildList"></select>

and finally, here is the javascript (which is also in the view) …

var children;
$(document).ready(function() {
    children = @Html.Raw(Json.Encode(Model.ChildList)) ;


function ParentChanged() {
    var parentID = parseInt($('#ParentList').val(), 10);
    var childItems = $.Enumerable.From(children)
        .Where(function(x) { return x.ParentID == parentID })
        .Select(function(x) { return { value: x.ID, text: x.Description } })
    var html = "<option id='-1'>(All Items)</option>";
    $.each(childItems, function(index, value) {
        html += "<option value='" + value.value + "'>" + value.text + "</option>";

So, all the work is done in the web browser. The dataset is relatively small so shouldn’t cause any memory issues. Obviously for larger datasets using ajax is the way to go, but for this particular case this solution works great.

One response to “Linq for Javascript / jQuery

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s