Saturday, May 23, 2015

JavaScript Takeaways for .Net Developers

1) Capture server controls where ClientIDMode is not set to Static

document.getElementById("<%= txtRule.ClientID %>").value

2) Storing Session value in JavaScript variable

var userAttempts = '<%= Session["userAttemptSession"] %>';


3) Manipulating Hidden field values

/*Get value*/
var hitCountContainer = document.getElementById("hdnMyCount")
var hitCount = parseInt(hitCountContainer.value);
hitCount = hitCount + 1;

/*Set Value*/
hitCountContainer.value = hitCount.toString()

4) Invoking a post-back (without any parameteres)

__doPostBack('', '');

5) Invoking post-back (including parameter passing)

__doPostBack('hdnMyCount', hitCount.toString());

Accessing the post-back parameters in Page_Init

string controlName = Request.Params["__EVENTTARGET"];
string controlValue = Request.Params["__EVENTARGUMENT"];

This example may be useful in a scenario where you need the client-side updated values during the Page_Init. Reason is that the values are not accessible at this point of the ASP.Net Page Life Cycle. If you need to access hidden fields during Page_Load this is not necessary as the values are already accessible by that time (of the ASP.Net Page Life Cycle). Dynamically generating Controls in an application page on user request (eg: add new row having ASP.Net controls) would be an ideal scenario.

FYI:
There is a nice little image of the ASP.Net Page Life Cycle in this MSDN Blog. Adorable isn't it ?   ;) The very essence of ASP.Net forms programming !!
         
6) Sending multiple parameters in JavaScript postback

Here I send two JavaScript variables count & type.

__doPostBack('addNew', JSON.stringify({ count: count.toString(), type: selectedText}));

In the server side capture using the following

/*Using directive*/
using System.Web.Script.Serialization
...
...
/*Code logic*/
string receivedArgs = Request.Params["__EVENTARGUMENT"];
var arguments = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(receivedArgs);
var countValue = arguments["count"];
var typeValue = arguments["type"];


1 comment: