Trong nhiều trường hợp, bạn cần lưu trữ đường dẫn của một file nhưng mà lại không biết cách lấy chúng trên server như thế nào trong Silverlight, vậy thì bài viết này sẽ chỉ cho bạn một cách làm đơn giản để get full file path nhé.
Edit HTML/ASPX Page
Đầu tiên là thêm đoạn script sau vào phần header
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <script type="text/javascript"> var silverlightCtrl = null; function pluginLoaded(sender, args) { silverlightCtrl = sender.getHost(); } function JS_GetFilePath() { document.getElementById("my_file_element").click(); } function sendPathToSL() { var element = document.getElementById("my_file_element"); silverlightCtrl.Content.SL2JS.SL_SetFilePath(element.value); } </script> |
Sau đó thêm cái này vào Silverlight object element
1 | <param name="onLoad" value="pluginLoaded" /> |
Và cuối cùng là thêm đoạn này vào thẻ body
1 2 3 | <form enctype="multipart/form-data" method="post" style="visibility:hidden; height:0px; width:0px; border:0px; overflow:hidden"> <input id="my_file_element" type="file" name="file_1" onchange="sendPathToSL();"> </form> |
Edit C# Class
Việc chúng ta cần làm bây giờ là:
1. Đăng ký một class bắt sự kiện của Javascript
1 | HtmlPage.RegisterScriptableObject("SL2JS", this); |
2. Invoke phương thức JS_GetFilePath
1 | System.Windows.Browser.HtmlPage.Window.Invoke("JS_GetFilePath"); |
3. Đợi nó trả lời 😀
1 2 3 4 5 | [ScriptableMember] public void SL_SetFilePath(string path) { Txt_Path.Text = path; } |
Chú ý: Bạn phải thêm thẻ [ScriptableMember] thì mới mong hoạt động nhé
Download code
Bạn có thể download đoạn code bên dưới về tham khảo nếu như hướng dẫn từ sharecodeweb không đủ làm cho bạn hiểu
You must log in to post a comment.