How to use String.Format function of C# in Javascript and display multiple values of a resource file.

Niladri.Biswas
Posted by in JavaScript category on for Beginner level | Points: 250 | Views : 7083 red flag

In this article we will look as how to use String.Format function of C# in JavaScript and display multiple values of a resource file.


 Download source code for How to use String.Format function of C# in Javascript and display multiple values of a resource file.

Introduction

Recently,I had a requirement where I need to access various values of resource file in javascript. So I thought of sharing the same here. In this article, we will look as how to display the current date and time using the C# DateTime.Now property in conjunction with reading some texts from resource files and combining them altogether using the String.Format C# function.

Straight to code

Let us first create a resource file (name it as "Test.resx") which has the following Names and Values

Next, create a Test.aspx page and have a button control. And on the OnClientClick event invoke a "Test()" function

	<asp:Button ID="btnTest" runat="server" Text="Invoke" OnClientClick="Test()" />

Lastly, implement the "Test()" funciton as under

<script language="javascript" type="text/javascript">
function Test() {
var combinedResourceValue = '<%= string.Format("{0}: {1} {2}: {3}", Resources.Test.Value1, DateTime.Now.ToString("MM/dd/yyyy") ,Resources.Test.Value2,DateTime.Now.ToString("HH:mm:ss tt")) %>';
alert(combinedResourceValue);
}
</script>

We can invoke the C# functions within a set of <%= and %> template operators.The output is as under

N.B.~The way to read resource file in java script is presented in Read Resource File values in JavaScript

Conclusion

So in this short article we have seen as how to use C# function, Resource file values in JavaScript. Hope, this will be useful.

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)