.NET Magazine國際中文電子雜誌
作 者:許薰尹
審 稿:張智凱
文章編號:N150115601
出刊日期:2015/01/14
開發工具:Visual Studio 2013 Ultimate Update 3
版本:.NET Framework 4.5.x
在此系列的文章第一篇《使用jQuery UI Autocomplete Widget連結遠端資料來源-1》中,我們介紹如何撰寫Web Form、Web服務當作jQuery UI Autocomplete Widget的伺服端程式,將滿足查詢條件的資料回傳。此篇文章將延續上一篇文章的情境,介紹如何使用WCF服務,以及如何利用Web API,和MVC的Action Method達到相同的功能。
使用WCF服務
現在我們來看一看使用WCF服務當做jQuery UI Autocomplete Widget伺服端程式的做法,延續前面的專案,加入一個WCF服務。從Visual Studio 2013開發工具-「Solution Explorer」視窗- 專案名稱上方按滑鼠右鍵,從快捷選單選擇「Add」- 「Add New Item」,開啟「Add New Item」對話盒,從右上方文字方塊輸入「wcf」搜尋,選取「WCF Service)」,設定名稱為「Service.svc」,然後按下「Add」按鈕,建立新服務,請參考下圖所示:
圖 1:建立新WCF服務。
在工具產生的IService.cs檔案之中,定義兩個方法,GetData方法使用WebGet Attribute開放給用戶端以HTTP Get方式呼叫,利用ResponseFormat設定資料交換格式為「json」;而GetDataByPOST方法則使用WebInvoke Attribute開放給用戶端以HTTP POST方式呼叫,利用UriTemplate 指定將接收一個term參數:
[ServiceContract]
public interface IService
{
[OperationContract]
[WebGet( ResponseFormat = WebMessageFormat.Json )]
List<string> GetData( string term );
[OperationContract]
[WebInvoke( Method = "POST" , ResponseFormat = WebMessageFormat.Json , UriTemplate = "GetDataByPOST/{term}" )]
List<string> GetDataByPOST( string term );
}
在Service.cs檔案的Service 類別中,實作IService 介面的GetData與GetDataByPOST方法,根據term關鍵字篩選符合條件的資料回傳:
public class Service : IService {
public List<string> GetData( string term ) {
string[ ] data = { "Microsoft" , "apple" , "Linux" , "Cisco" , "Oracle" , "Sun" , "Misc" };
var results = ( from d in data where d.ToUpper( ).StartsWith( term.ToUpper( ) ) select d ).ToList( );
return results;
}
public List<string> GetDataByPOST( string term ) {
string[ ] data = { "Microsoft" , "apple" , "Linux" , "Cisco" , "Oracle" , "Sun" , "Misc" };
var results = ( from d in data where d.ToUpper( ).StartsWith( term.ToUpper( ) ) select d ).ToList( );
return results;
}
}
測試一下服務是否能正常執行。從「Solution Explorer」視窗- 選取Service.svc檔案,按CTRL+F5執行,執行結果參考如下,你將看到一個WCF服務說明頁面,請參考下圖所示:

圖 2:WCF服務說明頁面。
下一步,我們要設定WCF使其可透過WebHTTPBinding讓用戶端以jQuery來進行呼叫。從Visual Studio 213 -「Solution Explorer」視窗- Web.Config檔案上方按滑鼠右鍵,從快捷選單選擇「Edit WCF Configuration」項目,請參考下圖所示:

圖 3:Edit WCF Configuration。
在「Adanvced」-「Protocol」選項,選取右方的「http」,按下方「Edit」按鈕,將「Binding」設定為「webHttpBinding」,然後按下「OK」按鈕,請參考下圖所示:

圖 4:將「Binding」設定為「webHttpBinding」。
在「Adanvced」-「Endpoint Behavior」選項上方按滑鼠右鍵,選取「New Endpoint Behavior Configuration」新增端點行為,請參考下圖所示:

圖 5:新增端點行為。
按「Add」按鈕,從清單中,選取「webHttp」,新增「webHttp」項目到右下方的清單之中,請參考下圖所示:

圖 6:新增「webHttp」項目。
設定完成之後,目前的Web.config檔案內容看起來如下:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433 -->
<configuration>
<system.web>
<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpGet"/>
</protocols>
</webServices>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
</system.web>
<system.serviceModel>
<protocolMapping>
<remove scheme="http" />
<add scheme="http" binding="webHttpBinding" />
</protocolMapping>
<behaviors>
<endpointBehaviors>
<behavior name="">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>
使用POST回傳 JSON 格式資料- ajax
現在我們來了解一下該如何使用jQuery與jQuery UI撰寫用戶端網頁的程式碼。在網頁之中,若要使用POST方式呼叫WCF服務回傳 JSON格式資料,可以利用以下程式碼,叫用ajax()方法,將term參數放在URL後方:
<!DOCTYPE html>
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="Content/themes/base/all.css" rel="stylesheet" />
</head>
<body>
<input type="text" name="myInput" id="myInput" />
<script src="Scripts/jquery-2.0.3.min.js"></script>
<script src="Scripts/jquery-ui-1.11.1.js"></script>
<script>
$( function () {
$( "#myInput" ).autocomplete( {
source: function ( request, callback ) {
var term = request.term;
var url = "Service.svc/GetDataByPOST/" + term;
$.ajax( {
type: "POST",
contentType: "application/json; charset=utf-8",
url: url,
async: false,
success: function ( data ) {
console.log( data );
callback( data );
}
} );
}
} );
} );
</script>
</body>
</html>
使用POST回傳 JSON格式資料 - post
jQuery另外提供一個post()方法可以直接送出HTTP POST請求,我們可以改寫上列用戶端程式碼如下,可以得到相同的執行效果:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="Content/themes/base/all.css" rel="stylesheet" />
</head>
<body>
<input type="text" name="myInput" id="myInput" />
<script src="Scripts/jquery-2.0.3.min.js"></script>
<script src="Scripts/jquery-ui-1.11.1.js"></script>
<script>
$( function () {
$( "#myInput" ).autocomplete( {
source: function ( request, callback ) {
var term = request.term;
var url = "Service.svc/GetDataByPOST/" + term;
$.post( url, function ( data ) {
console.log( data );
callback( data );
} );
}
} );
} );
</script>
</body>
</html>
使用GET回傳 JSON
若要使用HTTP GET方式呼叫WCF服務,取回JSON格式資料,只需要將term參數放在查詢字串之中傳遞即可,參考以下範例程式碼:
<!DOCTYPE html>
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="Content/themes/base/all.css" rel="stylesheet" />
</head>
<body>
<input type="text" name="myInput" id="myInput" />
<script src="Scripts/jquery-2.0.3.min.js"></script>
<script src="Scripts/jquery-ui-1.11.1.js"></script>
<script>
$( function () {
$( "#myInput" ).autocomplete( {
source: function ( request, callback ) {
var data = { term: request.term };
$.ajax( {
url: "Service.svc/GetData",
type: "get",
data: data,
async: false,
success: function ( data ) {
callback( data );
}
} );
}
} );
} );
</script>
</body>
</html>
ASP.NET Web API 服務
接下來我們來了解在伺服端,使用ASP.NET Web API來提供資料給jQuery UI Autocomplete Widget的做法。我們先建立一個ASP.NET Web API專案,從「File」-「New」-「Project」,在「New Project」對話盒中,確認視窗上方.NET Framework的目標版本為「.NET Framework 4.5.1」,選取左方「Installed」-「Template」-「Visual C#」或「Visual Basic」程式語言,從「Web」分類中,選取「ASP.NET Web Application」,設定專案名稱,按下「OK」鍵,請參考下圖所示:

圖 7:建立「MVC」與「Web API」專案。
由於後續文章將順便說明使用MVC的Action當伺服端程式的範例,因此在此步驟建專案時,先建立一個同時支援MVC與Web API的專案。從Visual Studio 2013 -「 File」-「New」-「Project」,在「New Project」對話盒中「New ASP.NET Project」對話盒中選取「Empty」,勾選下方的「MVC」與「Web API」項目,然後按下「OK」按鈕建立專案,請參考下圖所示:

圖 8:建立「MVC」與「Web API」專案。
完成這個動作之後,工具會自動在專案之中加入一個Global.asax檔案,並加入程式碼初始化MVC與Web API的路由:
namespace AutoCompleteDemo
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
工具產生的WebApiConfig.cs檔案中包含Web API路由註冊程式:
public static class WebApiConfig {
public static void Register( HttpConfiguration config ) {
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes( );
config.Routes.MapHttpRoute(
name: "DefaultApi" ,
routeTemplate: "api/{controller}/{id}" ,
defaults: new { id = RouteParameter.Optional }
);
}
}
}
RouteConfig.cs檔案中包含MVC路由註冊程式:
namespace AutoCompleteDemo {
public class RouteConfig {
public static void RegisterRoutes( RouteCollection routes ) {
routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" );
routes.MapRoute(
name: "Default" ,
url: "{controller}/{action}/{id}" ,
defaults: new { controller = "Home" , action = "Index" , id = UrlParameter.Optional }
);
}
}
}
接下來,在專案之中新增一個Web API控制器,從「Solution Explorer」視窗- 專案 -「Controllers」資料夾上方按滑鼠右鍵,從快捷選單選擇「Add」- 「Controller」,開啟「Add Scaffold」對話盒,請參考下圖所示:

圖 9:新增Web API控制器。
選取「Web API 2 Controller - Empty」,然後按下「Add」按鈕,請參考下圖所示:

圖 10:新增Web API控制器。
將名稱設定為「ValuesController」,然後按下「Add」按鈕,請參考下圖所示:

圖 11:設定控制器名稱。
Visual Studio會自動加入一個ValuesController類別,讓我們修改其中的程式碼,加入一個GetData方法,將滿足條件的資料篩選出來,轉換成集合之後回傳:
namespace AutoCompleteDemo.Controllers {
public class ValuesController : ApiController {
public IEnumerable<string> GetData( string term ) {
string[ ] data = { "Microsoft" , "apple" , "Linux" , "Cisco" , "Oracle" , "Sun" , "Misc" };
var results = ( from d in data where d.ToUpper( ).StartsWith( term.ToUpper( ) ) select d ).ToList( );
return results;
}
}
}
下載「jQuery」2.0.3版函式庫
用戶端的程式需要使用到jQuery與jQuery UI函式庫,我們可以使用Nuget套件管理員下載它們。在「Solution Explorer」視窗選取專案名稱。從Visual Studio 2013開發工具「TOOLS」-「Library Package Manager」-「Package Manage Console」開啟「Package Manage Console」視窗,然後在提示字元中輸入install-package指令,並使用「-version」指定安裝jQuery 2.0.3版本:
Install-Package jQuery -Version 2.0.3
下載「jQuery UI (Combined Library)」1.11.1版函式庫
使用Nuget套件管理員下載「jQuery UI (Combined Library)」1.11.1版函式庫。在「Solution Explorer」視窗選取專案名稱。從Visual Studio 2013開發工具「TOOLS」-「Library Package Manager」-「Package Manage Console」開啟「Package Manage Console」視窗,然後在提示字元中輸入install-package指令,並使用「-version」指定安裝jQuery UI (Combined Library) 1.11.1版本:
Install-Package jQuery.UI.Combined -Version 1.11.1
使用HTTP GET 方法取回JSON格式資料
現在我們可以撰寫用戶端的網頁了。從「Solution Explorer」視窗- 專案上方按滑鼠右鍵,從快捷選單選擇「Add」- 「New Item」,開啟「Add New Item」對話盒,從右上方文字方塊輸入「html」搜尋,選取「HTML Page」,設定名稱為然後按下「Add」按鈕,建立網頁。
在網頁中加入以下程式,使用HTTP GET 方法取回JSON格式的資料,只要指定Web API的URL位置,取回的資料可以直接給Autocomplete Widget使用:
<!DOCTYPE html>
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="Content/themes/base/all.css" rel="stylesheet" />
</head>
<body>
<input type="text" name="myInput" id="myInput" />
<script src="Scripts/jquery-2.0.3.js"></script>
<script src="Scripts/jquery-ui.min-1.11.1.js"></script>
<script>
$( function () {
$( "#myInput" ).autocomplete( {
source: function ( request, callback ) {
var data = { term: request.term };
$.ajax( {
url: "/api/values",
type: "get",
async: false,
data: data,
success: function ( result ) {
callback( result );
}
} );
}
} );
} );
</script>
</body>
</html>
使用HTTP GET 方法取回XML格式資料
若想要WEB API回傳XML格式資料,使用ajax方法時,可以設定dataType參數為「xml」,用戶端網頁程式改寫如下:
<!DOCTYPE html>
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="Content/themes/base/all.css" rel="stylesheet" />
</head>
<body>
<input type="text" name="myInput" id="myInput" />
<script src="Scripts/jquery-2.0.3.js"></script>
<script src="Scripts/jquery-ui.min-1.11.1.js"></script>
<script>
$( function () {
$( "#myInput" ).autocomplete( {
source: function ( request, callback ) {
var data = { term: request.term };
$.ajax( {
url: "/api/values",
type: "get",
dataType:"xml",
async: false,
data: data,
success: function ( xml ) {
console.log( xml );
var lists = [];
$( xml ).find( "string" ).each( function () {
lists.push( $( this ).text() );
} );
callback( lists );
}
} );
}
} );
} );
</script>
</body>
</html>
使用MVC Action Method回傳JSON格式資料
最後我們來了解一下,使用MVC Action Method回傳JSON格式資料的做法,延續之前的專案,在專案中加入一個MVC 控制器。從「Solution Explorer」視窗- 專案 -「Controllers」資料夾上方按滑鼠右鍵,從快捷選單選擇「Add」- 「Controller」,開啟「Add Scaffold」對話盒,選取「MVC 5 Controller - Empty」,然後按下「Add」按鈕,請參考下圖所示:

圖 12:加入一個MVC 控制器。
在「Add Controller」對話盒中,設定控制器名稱為「HomeController」;然後按下「Add 」按鈕,請參考下圖所示:

圖 13:設定控制器名稱為「HomeController」。
加入以下GetData方法回傳JSON格式資料,預設為了安全性理由,使用HTTP Get時不允許取回JSON格式資料,因此叫用Json方法時,你需要設定JsonRequestBehavior.AllowGet常數值開放存取:
namespace AutoCompleteDemo.Controllers {
public class HomeController : Controller {
// GET: Home
public ActionResult Index( ) {
return View( );
}
public ActionResult GetData( string term ) {
string[ ] data = { "Microsoft" , "apple" , "Linux" , "Cisco" , "Oracle" , "Sun" , "Misc" };
var results = ( from d in data where d.ToUpper( ).StartsWith( term.ToUpper( ) ) select d ).ToList( );
return Json( results , JsonRequestBehavior.AllowGet );
}
}
}
用戶端網頁程式改寫如下:
<!DOCTYPE html>
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="Content/themes/base/all.css" rel="stylesheet" />
</head>
<body>
<input type="text" name="myInput" id="myInput" />
<script src="Scripts/jquery-2.0.3.js"></script>
<script src="Scripts/jquery-ui.min-1.11.1.js"></script>
<script>
$( function () {
$( "#myInput" ).autocomplete( {
source: function ( request, callback ) {
var data = { term: request.term };
$.ajax( {
url: "/Home/GetData",
type: "get",
async: false,
data: data,
success: function ( result ) {
callback( result );
}
} );
}
} );
} );
</script>
</body>
</html>
總結
本系列文章介紹如何使用jQuery叫用遠端伺服器程式碼,將伺服端取回的資料當做jQuery UI Autocomplete Widget的資料來源,你可以利用各種伺服端的程式來提供資料篩選的功能,包含Web Forms、ASP.NET Web Service(ASMX)、WCF服務,以及ASP.NET Web API、MVC Action Method…等等技術。