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.
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.