Posts tagged ‘Javascript’

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

    [HttpGet]
    public ActionResult MyAction()
    {
        var parentList = _myRepository
            .GetParentList()
            .ToList()
            .Select(x => new SelectListItem
                              {
                                  Value = x.ID.ToString(),
                                  Text = x.Description,
                                  Selected = false
                              })
            .ToList();

        var childList = _myRepository
            .GetChildList()
            .ToList()
            .AsQueryable();

         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>
</div>

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

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

    $('#ParentList').change(ParentChanged);
});

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 } })
        .ToArray();
    var html = "<option id='-1'>(All Items)</option>";
    $.each(childItems, function(index, value) {
        html += "<option value='" + value.value + "'>" + value.text + "</option>";
    });
    $('#ChildList').empty().html(html);
}

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.

Yesterday I figured out a really neat feature of the RADWindow ASP.NET control from telerik.

Calling page

Javascript

function ItemWindowClosed(radWindow, returnValue)
{
var btnRefresh = FindObject(‘btnRefresh’);
if (btnRefresh != null)
{
btnRefresh.click();
}
}

ASPX

<radG:RadGrid ID=”itemsGrid” runat=”server”>
</radG:RadGrid>
<input
id=”btnRefresh”
type=”button”
value=”Refresh Grid”
onclick=’window["<%= itemsGrid.ClientID %>"].AjaxRequest(“<%= itemsGrid.UniqueID %>”, “Rebind”);’
style=”display:none;” />

Code-Behind

protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
base.RaisePostBackEvent(source, eventArgument);
switch (eventArgument)
{
case “Rebind”:
itemsGrid.Rebind();
break;
}
}

I used a hidden button because I have my javascript in a seperate file. If you embed your javascript within the aspx file then you could make the AjaxRequest call directly from within the ItemWindowClosed javascript function.

Dialog code

Javascript

var oWindow = GetRadWindow();
oWindow.CallBack();
oWindow.Close();

I had this in a response method to my OK and Cancel buttons. I actually wrapped it up in a little C# helper method to make things even simpler. All it does it register the above javascript as startupcode, so when the page is reloaded upon completion of the postback, the javascript code is executed. So my actual code was:-
WebHelper.CloseRadWindow(Page, “OK”);

I found a very interesting little trick today. When i’m creating a new page in a web application i do a lot of css editing. This usually involves making a change to my css file, saving it, going in to Internet Explorer and refreshing the page. Which if it’s an AJAX page can be annoying, as i will have to start from scratch every time i make a minor modification to the CSS.
The thing i stumbled upon today was a way to get Internet Explorer to reload just the css. This involved creating a bookmark/favourite with some embedded javascript in it. These little snippets of javascript are called bookmarklets or favelets.
The first solution for re-loading the CSS i found on the web would crash if run more than once within Internet Explorer. However, i have come up with a solution which i will now reveal to you!
During my travels around the web today i also stumbled across a jem of a page that takes normal javascript and “scrunches” it down into a bookmarklet/favelet.
In order to “install” the favelet, copy the below javascript, paste it into this page, pick a name for the favelet, click the Scrunch button and finally right-click the link it gives you and add it to your bookmarks/favourites.

var e = document.getElementsByTagName(‘link’);
var dt = new Date();

for (var i=0; i<e.length; i++)
{
if(e[i].rel.toLowerCase()==’stylesheet’)
{
var s = e[i].href.split(“?”);
if (s[0].match(/css$/))
{
e[i].href=”";
e[i].href=s[0];
}
}
}

I have tested this by knocking up a simple web page with an external css file, and it worked perfectly over several updates. I had to make it check the href ended with css, as i have some embedded stylesheets in one of my ASP.NET solutions and the links don’t end in css. The real trick was in getting IE to not crash when you run it more than once. That was achieved by clearing the href and then re-setting it again, rather than adding a random element to the href as part of a querystring.

This could easily be modified to refresh the CSS every x seconds. I have seen someone who did it every 2 seconds, but i think that’s a bit too often for my needs. It wouldn’t take much to write a pair of start/stop auto-refresh favelets.

Hope that helps someone out, it’s certainly going to make my life easier and save a lot of time.

I stumbled upon a useful little tip for examining the current html of a web page. This is very useful when the current state of a dynamic page needs to be looked at.
Basically, to look at the current html of a web page type the following into the address bar :-
javascript:’<xmp>’ + window.document.body.outerHTML + ‘</xmp>’
This can be done with firefox via the View Generated Source extension, so this is just an IE hack really.