:: Kunagorn Sirikup :: C# Developer

29/4/56

สร้าง AutoComplete ผ่าน WEB API ด้วย jQuery UI


1.สร้างโปรเจค ASP.NET MVC ขึ้นมา

2. Reference  .js และ .css ของ jQuery UI ไว้ที่ View หรือ _Layout


3. ใช่้ฟัง์ชั่น ajax ของ jQuery เพื่อดึงขอมูลจาก Api


ในกรณีที่ดึงข้อมูลเสร็จเรียบร้อย จะ Response ข้อมูลในรูปแบบ Json กลับมา แล้วนำมา Binding ลง DataSource ของ jQuery Autocomplete UI 


5.เท่านี้ก็สามารถสร้าง jQuery AutoComplet UI เสร็จเรียบร้อย


26/4/56

Action Filters with ASP.NET MVC

Filters เป็นอีก Feature สำคัญของ ASP.NET MVC เพราะช่วยลดกระบวนการในการทำงานของ Controller อย่างเช่น Security หรือ Logging เราจะกำหนด Filter Attribute ที่ Class , Method หรือ Property โดยแยกส่วนของ Security ออกจาก Action Method โดยใช้การ Filter แทน

Type of Filters
ปัจจุบัน ASP.NET MVC สามารถแบ่งการ Filter ได้เป็น 4 ประเภท คือ
1.Authorization Filters - ใช้ตรวจสอบการเข้าใช้งานของ User โดย Inherit IAuthorizationFilter

2.Action Filters - ประกอบด้วย Method OnActionExecuting โดยจะทำงานก่อนจะเกิด Action  และ OnActionExecuted  จะทำงานหลังจากเกิด Action  โดยทั้งสอง Method Inherit มาจาก IActionFilter

3.Result Filters - ประกอบด้วย Method OnResultExecuting โดยจะทำงานขณะ Executed Result  และ OnResultExecuted  จะทำงานหลังจาก Executed Result โดยทั้งสอง Method Inherit มาจาก ResultFilter

4.ExceptionFilters -  ประกอบด้วย Method OnException จะทำงานในระหว่างมีการ Execute Pipeline แล้วเกิดเหตุการณ์ Unhandled Exceptions ถูก Throw ออกมา  โดย Inherit Inherit มาจาก IExceptionFilter

ขั้นตอนการสร้าง Action Filters
1.สร้างโปรเจค ASP.NET MVC ขึ้นมา
2.สร้าง Folder Filters สำหรับเก็บ Class ที่จะทำ Acion Filter



3.สร้าง Class สำหรับทำ Action Filter ในที่นี้ขอยกตัวอย่างโดยสร้าง Action สำหรับ Customer ชื่อ ActionCustomerAttribute.cs โดย Inherit IActionFilter Interface และ FilterAttribute ที่เป็น BaseClass โดยอ้างอิงจาก namespace System.Web.Mvc


คำสั่ง "AttributeUsage" คือการกำหนดว่าเราสามารถ Filter ได้ที่ไหนบ้าง ในที่นี้ใช้คำสั่ง [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] หมายความว่า สามารถ Filter ได้ทั้ง Class และ Method

4. จากนั้นจะสามารถเพิ่ม Filter Attribute ได้ทั้ง Class และ Method เพื่อ Filter ว่าป็น Action ไหนได้


5.เมื่อมีการส่ง Result ที่กำหนด Filter Attribute ตรงกับที่สร้างไว้ ก็จะสามารถ Breakpoints เพื่อดูข้อมูล filterContext ได้


เมื่อกำหนด BreakPoint ไว้ที่ OnActionExecuted เพื่อตรวจสอบ ActionCustomer จะเห็นว่าสามารถดูข้อมูล Action ได้