All posts by Thiyagu

How to use javascript variables in C# and vise versa

Passing values from server to client side (code-behind to .aspx) for some manipulation using javascript and passing values from script to code behind are one of the most recurring tasks while developing the application. This scenario can be achieved in many ways. In this post we are going to see some techniques to achieve this.

1. Passing values from C# Code Behind to JavaScript.

You can use <%=variable%> to get value from aspx.cs. Variable must be public in aspx.cs file. For example, you can use: var date=”<%=DateTime.Now%>”; to get the server time.

Code behind :

public string value;

protected void Page_Load(object sender, EventArgs e)
{
value = “From Code-Behind”;
}

ASPX Code : Now, we going to display this variable Variable Cadebehindvalue into html page using javascript:

<script type=”text/javascript”>
$(document).ready(function() {
var Cadebehindvalue = ‘<%=value %>’;
var imagePath = <%=strImagePath %>;
alert(Cadebehindvalue);
});
</script>
</head>
<body>
<form id=”form1″ runat=”server”></form>
</body>

2. Passing parameter from C# Code Behind to javascript.

Using RegisterStartupScript we can write a JavaScript function in code behind and call it from code-behind or from HTML. Look at the code below for reference.

Syntax: RegisterStartupScript(Control, Type, String, String, Boolean)

Explanation :

Control : The control that is registering the client script block.
Type : The type of the client script block. This parameter is usually specified by using the typeof operator (C#) or the GetType operator (Visual Basic) to retrieve the type of the control that is registering the script.
Boolean : true to enclose the script block with <script> and </script> tags; otherwise, false.

CodeBehind :

String EmployeeID =”Aadharsh”;

ScriptManager.RegisterStartupScript(this, this.GetType(), “TestKey”, “TableTest(‘” + this.EmployeeID + “‘);”, true);

Java Script in aspx :

function TableTest(EMPID)
{
var width = 600;
var height = 330;
var left = 500;
var top = 100;
window.open(‘welcome.aspx?EMPID=’ + EMPID,’_blank’,’toolbar=no,menubar=no,resizable=no,scrollbars=auto,status=no,location=no,
width=’ + width + ‘,height=’ + height + ‘,left=’ + left + ‘,top=’ + top);
}

3. Passing values from JavaScript to C# Code Behind.

ASPX: Using HiddenField

<script type=”text/javascript”>
$(document).ready(function() {
alert($(“#hdfValue”).val());
});
</script>

inside the body tag

<form id=”form1″ runat=”server”>
<div>
<asp:HiddenField ID=”hdfValue” runat=”server” />
</div>
</form>

Codebehind

protected void Page_Load(object sender, EventArgs e)
{
hdfValue.Value = “Chnaged Value in codebehind”;
}

Image is not displaying in master page

Issue : Image is not displaying in master page

Solution :

If you use html control in master page as like below line

<img src=”~/App_Themes/Images/company_logo.png” width=”203″ height=”36″></div>

then we want to include runat attribute inside the image tag.

<img src=”~/App_Themes/Images/company_logo.png” runat=”server”  width=”203″ height=”36″></div>

else change the html control to asp control, then it will work in the master page

Note :

  • If you use the ~/ syntax then the control has to be a server control;so we want to include runat in the tag.

Copy data from div to ClipboardData using Jquery

How to copy div content form div to clipboard

Code Behind File :

Create string builder with some content and assign as like

divcontent.InnerHtml = sbQuestionAndAnswers.ToString();

Design File:

 <div id=”divcontent” style=” width: 1px; height: 1px;overflow:hidden;” runat=”server”></div>

Script File :

if (window.clipboardData && clipboardData.setData) {
if ($(‘#ctl00_cphMain_divcontent’)) {
$(‘#ctl00_cphMain_divcontent’).show();
var editableDiv = $(‘#ctl00_cphMain_divcontent’)

[0];
var txtRange = document.body.createTextRange();
editableDiv.style.display = “”;
txtRange.moveToElementText(editableDiv);
txtRange.select();
txtRange.execCommand(“Copy”);
editableDiv.style.display = “none”;//Hide the div
}}

Note :

Copying the content of div which is bind dynamically form code-behind and it will not display in the page. From that we copy content to clipboard

Nullable Types

Nullable Types

Nullable types are variables that can be assigned with the value ‘null’. Allmost all value types can be declared as a nullable type. To declare a
value type as a nullable type, you have to add a questionmark after the type name.

For example:

char? a = null;
bool? b = null;
int? c = null;
double? d = null;

Nullable type has two read-only properties: HasValue and Value.
HasValue is a bool property. If the current value is ‘null’,
HasValue will return false, otherwise it will return true. The HasValue property can be used to test if a variable contains a value.

For Example :

int? test = 10;
if (test .HasValue)
{
Console.WriteLine(test .Value);
}
else
{
Console.WriteLine(“no value”);
}

How to convert Nullable Type to NON-Nullable Type

int? intValue1 = null;
int intValue2  = intValue1  ?? 10;

Total minutes between two time value

How to get the difference of two time and get MM:SS of  time

Code Behind :

 DateTime locCurrentDateTime = System.DateTime.Now;
TimeSpan difference = locCurrentDateTime.Subtract(Convert.ToDateTime(Session[“starttime”]));
double hrs = Math.Floor(difference.TotalMinutes);
double sec = difference.Seconds;
string time = new DateTime(difference.Ticks).ToString(“mm:ss”);

Note :

output for above code will be find total minutes between two time and formatted as MM:SS

Finding the lable value after clicking the linkbutton inside the gridview

Finding the lable/any control value after clicking the linkbutton inside the gridview

Code Behind File :

  protected void btnClick_Click(object sender, EventArgs e)
{

GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblID = (Label)clickedRow.FindControl(“lblEmpID”);

Session

[“patientEMRID”] = lblID.Text;

}

Note :

First line we finding the clickable row and then finding the label value inside the gridview. lblEmpID is the id of the lable .

Calling severside method form script

How to call server side method button click event from the client side script :

Script :

<%= Page.ClientScript.GetPostBackEventReference(btnClose, String.Empty) %>;

Note :

Place this code in the script to call the any sever-side method, from above btnclose is the click method of the button. and event is empty.

Calling Script method from server side method.

System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), “Script”, “ConfirmationAlert();”, true);

Note :

ConfirmationAlert()  method :

 function ConfirmationAlert() {
var copiedText = “”;
var answer = confirm(“Click ‘OK’, to give alert!”)
if (answer) {
alert(“You Click OK”);}}

removeAttr() Method

.removeAttr()

Remove an attribute from each element in the set of matched elements.

HTML :

<table border=”1″>
<tr><td>This is first table</td></tr>
</table>

JQUERY:

$(document).ready(function() {

$(“table”).removeAttr(“border”);

});

OUTPUT DOM :

<table>
<tr><td>This is first table</td></tr>
</table>

NOTE :

From above JQ, removeAttr() remove th border attribute in the selected table

attr() Method

attr() :

The attr() method sets or returns attribute values of selected elements.

Getting attribute

JQUERY : 1

alert($(“#img1”).attr(“href”));

From above JQ, the message box will show the link of img1(which element having id as img1). Here its getting
value of attribute

Set attribute

JQUERY : 2

$(“#img1”).attr(“href”, “http://www.google.in”);

From above JQ, the link will apply to the href in to the element which having id as img1.

Example 1:

HTML :

<body><img /> <img /></body>

JQUERY :

$(“img”).attr({
src: “/image/test.gif”,
title: “jQuery attr() method”,
alt: “Not Available”
});

OUTPUT DOM :

<body>
<img src=”/image/test.gif” title=”jQuery attr() method” alt=”Not Available” />
<img src=”/image/test.gif” title=”jQuery attr() method” alt=”Not Available”/>
</body>