Oct 1 2009

ASP.Net MVC 1.0 and Html.CheckBox

Category: amilsark @ 18:40

With a background in ASP.Net web forms, the Html.CheckBox used with ASP.Net MVC did not behave how I thought it would.

For example when adding a checkbox to the View inside a table:

   1: <%=Html.CheckBox("cb" + item.player.idPlayer)%>

Firebug shows me this rendered in the html source of the page:

image


What is that hidden field for???


A developer on the Microsoft ASP.Net team said that this was by design so that we can properly assign a value of ‘false’ to an unchecked checkbox (link). 

I’m assuming this was the fix for the issue in the MVC 1.0 RC builds where a null value was being returning for unchecked checkboxes.


But in ASP.Net MVC 1.0, here is what the Request.Form values are (notice all checkbox inputs are listed with either a value of ‘false’ or ‘true’):

image

 


So in my case to loop through the returned inputs and grab the Player ID’s which have been checked:

Here is the controller action code to look for checked checkboxes (from Andrey Tkach on Stack Overflow):




   1: var selectedPlayerIds = new List<int>();
   2:             IEnumerable<Player> players;
   3:  
   4:             foreach (string key in Request.Form)
   5:             {
   6:                 var checkBox = String.Empty;
   7:                 if(key.StartsWith("cb"))
   8:                 {
   9:                     checkBox = Request.Form["" + key];
  10:                     if (checkBox != "false")
  11:                     {
  12:                         int id = Convert.ToInt32(key.Remove(0, 2));
  13:                         selectedPlayerIds.Add(id);
  14:                     }
  15:                 }
  16:             }





I am now able to use these playerID’s for interaction with the repository and perform interesting logic.

Tags: , ,

Sep 15 2009

How To: Retrieve Querystring Paramater Values Using Javascript

Category: amilsark @ 00:03

Javascript does not have a built in way to get querystring values easily in name, value pairs like ASP.Net.

 

So how do i get the “id” value in the URL  www.myurl.com/default.aspx?id=12345  ??

 

Here’s a javascript function which I found on multiple sites that works well.

   1: function GetQuerystringParam(name, url) {
   2:     name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
   3:     var regexS = "[\\?&amp;]" + name + "=([^&amp;#]*)";
   4:     var regex = new RegExp(regexS);
   5:     if (typeof (url) == 'undefined') url = window.location.href;
   6:     var results = regex.exec(url);
   7:     if (results == null)
   8:         return "";
   9:     else
  10:         return results[1];
  11: }

 

If you want to just use the browser’s current URL as the target querystring, see an example below.

   1: var value = GetQuerystringParam("id");    

 

Enjoy!

Tags: , , ,