webmatrix toggle checkboxes on server side

Because I wanted to toggle checkboxes using WebMatrix I almost gave in to using javascript because it seemed the most well known option,

Yet I really did not want to use JQUERY or any javascript for the checkbox toggle function.¬† I wanted to do everything from server side, like the ‘code behind’ of webforms. However the web pages are different in webMatrix, so I was not sure to proceed.

However i felt that in the long run, having the toggle run on the server would be better for this particular situation.

Webmatrix is the Microsoft development platform that uses razor syntax. I ultimately found the solution by slightly modifying a helper routine published by Mike Brind, Imar Spaanjaars in the book that I purchased¬† “Beginning ASP.net web Pages with WebMatrix”. WebmMatrix has evolved but the @helper code still works. Using that original code as the basis, I came up with a slightly modified, special ‘toggle version’. Here is an example of calling the helper function.

<input type="checkbox" name="items" value="1" @Helpers.CheckedToggle("items", "1") />

And here is the checkedToggle helper which toggles the checkboxes.

@helper CheckedToggle(string option, string value)
        if (HttpContext.Current.Request[option] != null)
            var values = HttpContext.Current.Request[option].Split(',');
            if (!values.Contains(value))
        else {<text>checked=\"checked\"</text>}

I’m not sure if the code will fit other situations as mine but maybe it will help someone else looking for a toggle routine to handle checkboxes.