ASP.NET Web API 的简单示例
Demo1:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Comments Test Home Page</title>
<link href="/Content/Demo.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="/Scripts/knockout-2.1.0.js" type="text/javascript"></script> <script type="text/javascript" src="/Scripts/demo1/get.js"></script>
</head>
<body>
<nav>
<div class="demo-navigation">
<a href="default.htm"><<< Back</a>
| Demo 1 Simple Get |
<a href="demo2-crud.htm">On to Demo 2 - Simple CRUD >>></a>
</div>
</nav>
<div id="content"> <div id="demo-actions">
<div>
<legend>Get Comments Demos</legend>
<button id="getComments">Go!</button>
</div>
</div>
<div id="article">
<p>
This first demo shows a very simple GET scenario. Click on the button to
use jQuery to retrieve JSON data from a Web API endpoint and then display
the contents of that payload in the UI.
</p>
<p>
The code represents retrieving data in a manner that any developer familiar
with jQuery would understand.
</p>
</div> <ul data-bind="template: {name: 'commentTemplate', foreach: comments}">
</ul> <script id="commentTemplate" type="text/html">
<li class="comment">
<header>
<div class="info">
<img data-bind="attr: {src: GravatarUrl}" />
<strong><span data-bind="text: Author"></span></strong>
</div>
</header>
<div class="body">
<p data-bind="text: Text"></p> </div>
</li>
</script> <script type="text/javascript">
viewModel = {
comments: ko.observableArray([])
}; ko.applyBindings(viewModel);
</script>
</div>
</body>
</html>
JS:
$(function() {
$("#getComments").click(function () {
// We're using a Knockout model. This clears out the existing comments.
viewModel.comments([]); $.get('/api/comments', function (data) {
// Update the Knockout model (and thus the UI) with the comments received back
// from the Web API call.
viewModel.comments(data);
}); });
});
Demo2:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Comments Test Home Page</title>
<link href="/Content/Demo.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="/Scripts/knockout-2.1.0.js" type="text/javascript"></script> <script type="text/javascript" src="/Scripts/demo2/get.js"></script>
<script type="text/javascript" src="/Scripts/demo2/post.js"></script>
<script type="text/javascript" src="/Scripts/demo2/delete.js"></script>
</head>
<body>
<nav>
<div class="demo-navigation">
<a href="demo1-simpleget.htm"><<< Back</a>
| Demo 2 CRUD |
<a href="demo3-paging.htm">On to Demo 3 - Paging >>></a>
</div>
</nav>
<div id="content">
<div id="article">
<p>
See, I told you that last demo would be simple.
</p>
<p>
This demo allows the user to create and delete comments. When we
delete the comment, we use a proper HTTP DELETE request. Again, the
code is still very simple. Note that when we POST a comment, we handle
the proper 201 status code.
</p>
</div>
<ul data-bind="template: {name: 'commentTemplate', foreach: comments}">
</ul>
<form id="newCommentForm">
<fieldset>
<legend>New Comment</legend>
<label for="text">Comment</label>
<textarea id="text" name="text" type="text"></textarea>
<label for="author">Author</label>
<input id="author" name="author" type="text" value="" />
<label for="email">Email</label>
<input id="email" name="email" type="text" value="" />
<button type="submit">Submit</button>
</fieldset>
</form>
<script id="commentTemplate" type="text/html">
<li class="comment">
<header>
<div class="info">
<img data-bind="attr: {src: GravatarUrl}" />
<strong><span data-bind="text: Author"></span></strong>
</div>
<div class="actions">
<a class="delete" data-bind="attr: { 'data-comment-id': ID }" href="#">Delete Id: <span data-bind="text: ID" /></a>
</div>
</header>
<div class="body">
<p data-bind="text: Text"></p> </div>
</li>
</script>
<script type="text/javascript">
viewModel = {
comments: ko.observableArray([])
}; ko.applyBindings(viewModel);
</script>
</div>
</body>
</html>
JS:
get.js
$(function() {
// We're using a Knockout model. This clears out the existing comments.
viewModel.comments([]); $.get('/api/comments', function (data) {
// Update the Knockout model (and thus the UI) with the comments received back
// from the Web API call.
viewModel.comments(data);
});
});
post.js
$(function () {
var form = $('#newCommentForm');
form.submit(function () {
var form = $(this);
var comment = { ID: 0, Text: $('#text').val(), Author: $('#author').val(), Email: $('#email').val(), GravatarUrl: '' };
var json = JSON.stringify(comment); $.ajax({
url: '/api/comments',
cache: false,
type: 'POST',
data: json,
contentType: 'application/json; charset=utf-8',
statusCode: {
201 /*Created*/: function (data) {
viewModel.comments.push(data);
}
}
}); return false;
});
});
delete.js
$(function() {
$("a.delete").live('click', function () {
var id = $(this).data('comment-id'); $.ajax({
url: "/api/comments/" + id,
type: 'DELETE',
cache: false,
statusCode: {
200: function(data) {
viewModel.comments.remove(
function(comment) {
return comment.ID == data.ID;
}
);
}
}
}); return false;
});
});
Demo3:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Comments Test Home Page</title>
<link href="/Content/Demo.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="/Scripts/knockout-2.1.0.js" type="text/javascript"></script> <script type="text/javascript" src="/Scripts/demo3/get-querystring.js"></script>
<script type="text/javascript" src="/Scripts/demo3/get-queryable.js"></script>
</head>
<body>
<nav>
<div class="demo-navigation">
<a href="demo2-crud.htm"><<< Back</a>
| Demo 3 Paging |
<a href="demo4-validation.htm">On to Demo 4 - Validation >>></a>
</div>
</nav>
<div id="content"> <div id="demo-actions">
<div>
<legend>Paging Demos</legend>
<label for="pageSize">Size:</label> <input type="input" id="pageSize" class="paging" value="4" />
<label for="pageIndex">Index:</label> <input type="input" id="pageIndex" class="paging" value="0" /> <button id="getCommentsPaging">Query String</button>
<button id="getCommentsQueryable">Queryable</button>
</div>
</div> <div id="article">
<p>
This is a demo of paging through data.
</p>
<p>
The "Query String" button calls code that demonstrates how a typical developer
might implement paging today.
</p>
<p>
The "Queryable" button turns it up a notch and shows paging using a service method
that returns an <code>IQueryable</code>. Note that the client code hasn't changed
much at all, but the server code is much simpler.
</p> </div> <ul data-bind="template: {name: 'commentTemplate', foreach: comments}">
</ul> <script id="commentTemplate" type="text/html">
<li class="comment">
<header>
<div class="info">
<img data-bind="attr: {src: GravatarUrl}" />
<strong><span data-bind="text: Author"></span></strong>
</div>
</header>
<div class="body">
<p data-bind="text: Text"></p> </div>
</li>
</script> <script type="text/javascript">
viewModel = {
comments: ko.observableArray([])
}; ko.applyBindings(viewModel);
</script>
</div>
</body>
</html>
JS:
get-querystring.js
$(function () {
//---------------------------------------------------------
// Using custom Query String parameters to page
//---------------------------------------------------------
$("#getCommentsPaging").click(function () {
viewModel.comments([]); var pageSize = $('#pageSize').val();
var pageIndex = $('#pageIndex').val(); var url = "/api/comments?pageSize=" + pageSize + '&pageIndex=' + pageIndex; $.getJSON(url, function (data) {
// Update the Knockout model (and thus the UI) with the comments received back
// from the Web API call.
viewModel.comments(data);
}); return false;
});
});
get-queryable.js
$(function () {
//---------------------------------------------------------
// Using Queryable to page
//---------------------------------------------------------
$("#getCommentsQueryable").click(function () {
viewModel.comments([]); var pageSize = $('#pageSize').val();
var pageIndex = $('#pageIndex').val(); var url = "/api/comments?$top=" + pageSize + '&$skip=' + (pageIndex * pageSize); $.getJSON(url, function (data) {
// Update the Knockout model (and thus the UI) with the comments received back
// from the Web API call.
viewModel.comments(data);
}); return false;
});
});
Demo4:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Comments Test Home Page</title>
<link href="/Content/Demo.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="/Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script> <script type="text/javascript" src="/Scripts/demo4/get.js"></script>
<script type="text/javascript" src="/Scripts/demo4/post.js"></script>
<script type="text/javascript" src="/Scripts/demo4/delete.js"></script>
</head>
<body>
<nav>
<div class="demo-navigation">
<a href="demo3-paging.htm"><<< Back</a>
| Demo 4 Validation |
<a href="demo5-authorization.htm">On to Demo 5 - Authorization >>></a>
</div>
</nav>
<div id="content"> <div id="article">
<p>
In this demo, we take advantage of the unobtrusive client validation introduced in
ASP.NET MVC and apply it to a static HTML page.
</p>
<p>
Once you pass the client validation rules, note that we also support validation
happening on the server. If there are any validation errors, we serialize the
model state to JSON and apply the validation back on the client.
</p>
<p>
<strong>After submitting a valid comment, try typing in an author that's more
than 10 characters long.</strong>
</p>
</div>
<ul data-bind="template: {name: 'commentTemplate', foreach: comments}">
</ul>
<form id="newCommentForm">
<fieldset>
<legend>New Comment</legend>
<label for="text">Comment</label>
<textarea id="text" name="text" data-val="true" data-val-required="A comment is required."></textarea>
<span class="field-validation-valid" data-valmsg-for="text" data-valmsg-replace="true"></span> <label for="author">Author</label>
<input id="author" name="author" type="text" data-val="true" data-val-required="Tell us who you are." value="" />
<span class="field-validation-valid" data-valmsg-for="author" data-valmsg-replace="true"></span> <label for="email">Email</label>
<input id="email" name="email" type="text" data-val="true" data-val-required="What's your email address?" value="" />
<span class="field-validation-valid" data-valmsg-for="email" data-valmsg-replace="true"></span>
<button type="submit">Submit</button>
</fieldset>
</form> <script id="commentTemplate" type="text/html">
<li class="comment">
<header>
<div class="info">
<img data-bind="attr: {src: GravatarUrl}" />
<strong><span data-bind="text: Author"></span></strong>
</div>
<div class="actions">
<a class="delete" data-bind="attr: { 'data-comment-id': ID }" href="#">Delete Id: <span data-bind="text: ID" /></a>
</div>
</header>
<div class="body">
<p data-bind="text: Text"></p>
</div>
</li>
</script>
<script type="text/javascript">
viewModel = {
comments: ko.observableArray([])
}; ko.applyBindings(viewModel);
</script>
</div>
</body>
</html>
JS:
get.js
$(function () {
// We're using a Knockout model. This clears out the existing comments.
viewModel.comments([]); $.get('/api/comments', function (data) {
// Update the Knockout model (and thus the UI) with the comments received back
// from the Web API call.
viewModel.comments(data);
});
});
post.js
$(function () {
$.validator.addMethod("failure", function () { return false; });
$.validator.unobtrusive.adapters.addBool("failure");
$.validator.unobtrusive.revalidate = function (form, validationResult) {
$.removeData(form[0], 'validator');
var serverValidationErrors = [];
for (var property in validationResult) {
var elementId = property.toLowerCase();
elementId = elementId.substr(elementId.indexOf('.') + 1);
var item = form.find('#' + elementId);
serverValidationErrors.push(item);
item.attr('data-val-failure', validationResult[property][0]);
jQuery.validator.unobtrusive.parseElement(item[0]);
}
form.valid();
$.removeData(form[0], 'validator');
$.each(serverValidationErrors, function () {
this.removeAttr('data-val-failure');
jQuery.validator.unobtrusive.parseElement(this[0]);
});
} var form = $('#newCommentForm');
form.submit(function () {
var form = $(this);
if (!form.valid()) {
return false;
} var comment = { ID: 0, Text: $('#text').val(), Author: $('#author').val(), Email: $('#email').val(), GravatarUrl: '' };
var json = JSON.stringify(comment); $.ajax({
url: '/api/comments',
cache: false,
type: 'POST',
data: json,
contentType: 'application/json; charset=utf-8',
statusCode: {
201 /*Created*/: function (data) {
viewModel.comments.push(data);
},
400 /* BadRequest */: function (jqxhr) {
var validationResult = $.parseJSON(jqxhr.responseText);
$.validator.unobtrusive.revalidate(form, validationResult.ModelState);
}
}
}); return false;
});
});
delete.js
$(function() {
$("a.delete").live('click', function () {
var id = $(this).data('comment-id'); $.ajax({
url: "/api/comments/" + id,
type: 'DELETE',
cache: false,
statusCode: {
200: function(data) {
viewModel.comments.remove(
function(comment) {
return comment.ID == data.ID;
}
);
}
}
}); return false;
});
});
Demo5:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Comments Test Home Page</title>
<link href="/Content/Demo.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="/Scripts/knockout-2.1.0.js" type="text/javascript"></script> <script type="text/javascript" src="/Scripts/demo5/get-formsauth.js"></script>
</head>
<body>
<nav>
<div class="demo-navigation">
<a href="demo4-validation.htm"><<< Back</a>
| Demo 5 Authorization |
</div>
</nav>
<div id="content">
<div id="demo-actions">
<div>
<legend>Authorization</legend>
<button id="getCommentsFormsAuth">Forms Authentication</button>
</div>
</div> <div id="article">
<p>
<strong>Forms Authentication</strong> demonstrates calling a service method that
requires authentication using Forms Authentication. To require authentication for the
Web API uncomment the <code>[Authorize]</code> attribute on the
<code>CommentsController</code>.
</p>
</div> <ul data-bind="template: {name: 'commentTemplate', foreach: comments}">
</ul> <script id="commentTemplate" type="text/html">
<li class="comment">
<header>
<div class="info">
<img data-bind="attr: {src: GravatarUrl}" />
<strong><span data-bind="text: Author"></span></strong>
</div>
</header>
<div class="body">
<p data-bind="text: Text"></p> </div>
</li>
</script> <script type="text/javascript">
viewModel = {
comments: ko.observableArray([])
}; ko.applyBindings(viewModel);
</script>
</div>
</body>
</html>
JS:
get-formsauth.js
$(function () {
$("#getCommentsFormsAuth").click(function () {
viewModel.comments([]);
$.ajax({ url: "/api/comments",
accepts: "application/json",
cache: false,
statusCode: {
200: function(data) {
viewModel.comments(data);
},
401: function(jqXHR, textStatus, errorThrown) {
self.location = '/Account/Login/';
}
}
});
});
});
下载地址:http://code.msdn.microsoft.com/ASPNET-Web-API-JavaScript-d0d64dd7
谢谢浏览!
ASP.NET Web API 的简单示例的更多相关文章
- ASP.NET Web API 控制器创建过程(一)
ASP.NET Web API 控制器创建过程(一) 前言 在前面对管道.路由有了基础的了解过后,本篇将带大家一起学习一下在ASP.NET Web API中控制器的创建过程,这过程分为几个部分下面的内 ...
- ASP.NET Web API Selfhost宿主环境中管道、路由
ASP.NET Web API Selfhost宿主环境中管道.路由 前言 前面的几个篇幅对Web API中的路由和管道进行了简单的介绍并没有详细的去说明一些什么,然而ASP.NET Web API这 ...
- ASP.NET Web API 管道模型
ASP.NET Web API 管道模型 前言 ASP.NET Web API是一个独立的框架,也有着自己的一套消息处理管道,不管是在WebHost宿主环境还是在SelfHost宿主环境请求和响应都是 ...
- ASP.NET Web API 路由对象介绍
ASP.NET Web API 路由对象介绍 前言 在ASP.NET.ASP.NET MVC和ASP.NET Web API这些框架中都会发现有路由的身影,它们的原理都差不多,只不过在不同的环境下作了 ...
- 简话ASP.NET Web API
简话ASP.NET Web API 在vs2012中,我们很容易在根据选择的ASP.NET MVC Web应用程序来新建一个Web API应用,聪明的你一定想见得到,Web API和MVC有着某种联系 ...
- 杂项:ASP.NET Web API
ylbtech-杂项:ASP.NET Web API ASP.NET Web API 是一种框架,用于轻松构建可以访问多种客户端(包括浏览器和移动设备)的 HTTP 服务. ASP.NET Web A ...
- ASP.NET Web API WebHost宿主环境中管道、路由
ASP.NET Web API WebHost宿主环境中管道.路由 前言 上篇中说到ASP.NET Web API框架在SelfHost环境中管道.路由的一个形态,本篇就来说明一下在WebHost环境 ...
- 支持Ajax跨域访问ASP.NET Web Api 2(Cors)的简单示例教程演示
随着深入使用ASP.NET Web Api,我们可能会在项目中考虑将前端的业务分得更细.比如前端项目使用Angularjs的框架来做UI,而数据则由另一个Web Api 的网站项目来支撑.注意,这里是 ...
- 【翻译】使用Knockout, Web API 和 ASP.Net Web Forms 进行简单数据绑定
原文地址:http://www.dotnetjalps.com/2013/05/Simple-data-binding-with-Knockout-Web-API-and-ASP-Net-Web-Fo ...
随机推荐
- javaweb学习总结(二十)——JavaBean总结
一.什么是JavaBean JavaBean是一个遵循特定写法的Java类,它通常具有如下特点: 这个Java类必须具有一个无参的构造函数 属性必须私有化. 私有化的属性必须通过public类型的方法 ...
- 【锁】Oracle锁系列
[锁]Oracle锁系列 1 BLOG文档结构图 2 前言部分 2.1 导读和注意事项 各位技术爱好者,看完本文后,你可以掌握如下的技能,也可以学到一些其它你所不知道的知识,~O(∩_∩)O~: ...
- Windows Server 安装 BitLocker
打开PowerShell(管理员): C:\> Install-WindowsFeature BitLocker -Restart 安装好后,系统会自动重新启动. Windows Server ...
- css解决谷歌,360浏览器默认最小字体为12px问题
当我们设置前台html页面样式问题字体小于12px;时,会发现不管怎么设置小于12px字体,在谷歌.360浏览器上都不生效. 但在火狐等浏览器上却可以正常设置,当你打开谷歌360的设置后会发现,它们设 ...
- 不能返回函数内部new分配的内存的引用
以前在开发电子秤接口动态库时,曾尝试在用于获取重量的函数外面定义一个字符串指针,然后作为参数传入函数内部,然后在函数内部new,用来输出函数执行过程中发生的错误.但是总是出错,没有找到原因,后来无意中 ...
- PHP实现微信公众账号开发
1.首先需要一个可以外网访问的接口url. 我这里是申请的新浪免费云服务器,http://xxxxx.applinzi.com/wx.php,具体自己可以去新浪云中心申请地址为:http://www. ...
- AndroidManifest常见的设置解析
AndroidManifest.xml清单文件是每个Android项目所必需的,它是整个Android项目的全局描述文件.AndroidManifest.xml清单文件说明了该应用的名称.所使用的图标 ...
- Android JNI HelloWorld实现
创建一个JNIDemo的Android工程 在项目下创建一个文件夹jni.(注意必须是jni目录) 在jni目录下创建两个文件:Android.mk 和 first_jni.c(.c文件的名字可以任意 ...
- 多功能表单填报系统V1.2.1-适用于在线报名系统、调查、数据收集等
多功能表单系统V1.2.1 前台:http://www.schoolms.net/mysoft/biaodan/index.asp 后台:http://www.schoolms.net/myso ...
- Docker实践(4)—network namespace与veth pair
network namespace 创建network namespace # ip netns add blue # ip netns list blue 添加网口到namespace 先创建v ...