レストサービス
完全なアプリケーションは、次の場所からダウンロードできます。
http://sdrv.ms/LJJz1K
このサンプルでは、ASP.Net のレスト サービスを使用します (同じ概念を MVC アプリケーションに適用できます)。
残りのサービスとページ メソッドを使用する場合の明確な利点は、テスト容易性です。
サービスを構成する手順を順を追って説明します。
次の参照が必要です。
- System.Web.ServiceModel.dll
- System.Web.ServiceModel.Activation.dll
- System.Web.ServiceModel.Web.dll
ナゲットパッケージ:
jQuery プラグイン:
サービス情報
[ServiceContract]
public interface IMyService
{
[OperationContract]
[WebInvoke(
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "/DeleteFromService",
Method = "DELETE")]
void Delete(int id);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
{
public void Delete(int id)
{
// delete your product
// simulate a long process
Thread.Sleep(5000);
}
}
Global.asax で
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");
RouteTable.Routes.Add(new ServiceRoute("",
new WebServiceHostFactory(),
typeof(MyService)));
}
web.config 内
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true"
automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
スクリプトの登録 (マスターページに登録可能)
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js" language="javascript" ></script>
<script language="javascript" type="text/javascript" src="Scripts/jquery.blockui.1.33.js"></script>
ASP.Net コンテンツ ページ (このサンプルでは、マスター ページを使用しています)
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<input type="button" value="Delete" id="myButton" />
</asp:Content>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript" language="javascript">
function deleteFromService() {
if (!confirm("Are you sure you want to delete?")) {
return;
}
$.blockUI();
$.ajax({
cache: false,
type: "DELETE",
async: true,
url: "/DeleteFromService",
data: "3", // get your id to delete
contentType: "application/json",
dataType: "json",
success: function () {
$(document).ajaxStop($.unblockUI);
alert("done");
},
error: function (xhr) {
$(document).ajaxStop($.unblockUI);
alert(xhr.responseText);
}
});
}
jQuery().ready(function () {
$("#myButton").click(deleteFromService);
});
</script>
</asp:Content>
それだけです。ajax は簡単な方法でコマンドを実行します =)