จากเนื้อหาเก่า Method Post on Code Behide with asp.net มีปัญหาในการส่งข้อมูลประเภทภาษาไทย ดังนั้นในส่วนของการ encode ให้ทำแบบนี้ วิธีนี้ได้มาจาก krucode.net ครับ
1
2
| System.Text.Encoding encoder= System.Text.Encoding.GetEncoding(65001);
byte[] byteData = encoder.GetBytes(outputBuffer); |
เมื่อเอามารวมกันเต็มๆก็จะเป็นแบบโค๊ดด้านล่างครับ
1
2
3
4
5
6
7
8
9
10
11
12
13
| string responseString = "";
string outputBuffer = string.Format("msg={0}&senderemail={1}&sendername={2}&tel={3}",mail.Msg, mail.SenderEmail, mail.SenderName, mail.Tel);
WebClient postWebClient = new WebClient();
postWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string postUrl = "http://localhost:53680/aspgod/contact_receive.aspx";
// encode
System.Text.Encoding encoder= System.Text.Encoding.GetEncoding(65001);
byte[] byteData = encoder.GetBytes(outputBuffer);
byte[] responseArray = postWebClient.UploadData(postUrl, "POST", byteData);
responseString = System.Text.Encoding.ASCII.GetString(responseArray);
Response.Write(responseString); |
สำหรับคนที่ส่งสัยว่าทำไมต้องเป็นเลข 65001 ให้ตามมาดูที่ System.Text.Encoding.GetEncoding(WhatValidStrings) ได้เลยครับ
การส่งข้อมูลระหว่าง page สามารถทำได้ 2 วิธี
1. get method
2. post method
สำหรับแบบ get ใครๆก็ทำได้ แค่เรียก url แล้วใส่ parameter ตามหลังไป เช่น www.aspgod.com/view.aspx?id=30 กรณีนี้อาจไม่ปลอดภัยเพราะแค่เปลี่ยน parameter ก็สามารถเข้าถึงหน้าต่างๆได้ หากเราต้องการความปลอดภัยของข้อมูลที่มากกว่านี้ แนะนำให้ใช้ method post
การส่งแบบ post โดยปกติในรูปแบบของ html ก็สามารถทำได้ง่ายแค่เปลี่ยนหัวของ form แต่หากเป็น aspx และเราต้องการนำข้อมูลนั้นๆมาประมวลผลก่อนแล้วค่อยส่งไปหน้าอื่นๆ เราต้องทำผ่าน code behide แล้วค่อยส่งข้อมูลไปยังหน้าอื่นโดยใช้ WebClient เข้ามาช่วย ตามตัวอย่างข้างล่างเลยครับ
1
2
3
4
5
6
7
8
9
10
| string responseString = "";
string outputBuffer = string.Format("msg={0}&senderemail={1}&sendername={2}&tel={3}",mail.Msg, mail.SenderEmail, mail.SenderName, mail.Tel);
WebClient postWebClient = new WebClient();
postWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string postUrl = "http://localhost:53680/aspgod/contact_receive.aspx";
byte[] byteData = System.Text.Encoding.Default.GetBytes(outputBuffer);
byte[] responseArray = postWebClient.UploadData(postUrl, "POST", byteData);
responseString = System.Text.Encoding.ASCII.GetString(responseArray);
Response.Write(responseString); |
เป็นระบบส่ง mail โดยการส่งไปให้หน้า contact_receive.aspx เป็นผู้ส่งเมลล์ให้ หากส่งสำเร็จก็จะ Response.Write(“success”); กลับมา ทำให้เราตรวจสอบได้ว่าถูกต้องหรือไม่ หากทำตามตัวอย่างนี้ก็สามารถส่งข้อมูลผ่าน method post ด้วย code behide ได้ครับ