Resource in javascript using HttpHandler
אז כתבנו Resource file, והכנסנו לתוכו את כל ההודעות שלנו,
ואפילו הגדרנו אותו כ public, כדי שנוכל לגשת אליו מכל הפרויקטים,
אבל מה אנחנו עושים, עם ההודעות שאנחנו רוצים להציג ב JavaScript,
אז הנה הפיתרון:
בפרויקט שאפשר להוריד
מכאן:
יש פרויקט שנקרא Common, שבו יש את ה resource file,
הוספנו בפרויקט ה web, קובץ מסוג HttpHandler,
שקורא את כל המאפיינים של ה Resource, ומחזיר מערך JS, עם כל הערכים.
הנה הקוד:
1 public void ProcessRequest(HttpContext context)
2 {
3 context.Response.ContentType = "application/js";
4
5 // Get the type of the resource class
6 Type messagesType = typeof(Messages);
7
8 // Get the all properties taht is public and static
9 PropertyInfo[] properties = messagesType.GetProperties(
10 BindingFlags.Public | BindingFlags.Static);
11
12 // Get a collection of Pair,
13 // the first is the property name, and the secound is the property value
14 var stringProperties =
15 from property in properties
16 where property.PropertyType == typeof(string)
17 select new Pair(property.Name, property.GetValue(null, null));
18
19
20 // Build the javascript array
21 StringBuilder bulder = new StringBuilder();
22 bulder.Append("var messageArray = new Array(); ");
23
24 foreach (var item in stringProperties)
25 {
26 bulder.Append(string.Format("messageArray['{0}'] = '{1}'; ",
27 item.First, item.Second));
28 }
29
30 context.Response.Write(bulder.ToString());
31 }
אז מה כתוב בקוד:
שורה 3: הגדירה שמה שחוזר הוא מסוג JavaScript
שורה 6: קבלת ה Type של Messages (קובץ ה Resource)
שורה 9: קבלת כל המאפיינים שמוגדרים כ: public static
שורה 14 - 17: קבלת Collection של Pair, שמכיל את השם של המאפיין, ואת ערכו. (null, null בשורה 17, זה בגלל שהמאפיין הוא סטטי, ולא indexer)
שורה 21: הגדרת ה StringBuilder, שיכיל את המערך ה JS.
שורה 22: הגדרת המערך ב JS.
שורה 24 - 28: ריצה על כל המאפיינים שקבלנו, ולהוסיף אותם למערך.
שורה 30: כתיבה של המערך ל Response.
השימוש בצד ה Web, יהיה פשוט:
1 <script src="MessageHandler.ashx" type="text/javascript"></script>
2 <script type="text/javascript">
3 function Show() {
4 alert(messageArray['Name']);
5 alert(messageArray['Address']);
6 }
7 </script>
ייבוא של ה JS, מתוך ה httpHandler.
ואז פשוט להשתמש במערך.
תהנו