mvcAPI (入门 2)

时间:2023-03-09 06:54:34
mvcAPI (入门 2)

1)建立一个实体类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace MvcApplication23.Models
{
public class UserInfo
{
public int Id { get; set; } public string Name { get; set; } public int Age { get; set; }
}
}

实体类

2)建立API控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication23.Models;
using System.Web.Http; namespace MvcApplication23.Controllers
{
public class HomeController :ApiController
{
//
// GET: /Home/ public List<UserInfo> GetUser()
{
var userList = new List<UserInfo>{
new UserInfo{ Id=, Name="lidu1", Age=},
new UserInfo{ Id=, Name="lidu2", Age=},
new UserInfo{ Id=, Name="lidu3", Age=}
};
var temp = (from u in userList select u).ToList();
return temp;
} }
}

API控制器

这时候 可以在地址栏中输入url 可以看见效果了 :http://localhost:42571/api/Home/GetUser

3)测试客户端 效果 或者展示

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="Scripts/jquery-1.8.2.js"></script>
<script>
$(function () {
$.ajax({
type: "Get",
dataType: "json",
contentType: "application/json;charset=utf-8",
url: "/api/Home/GetUser",
success: function (data) {
var tbody = $("#tbody1");
$.each(data, function (idx, item) {
OutputData(tbody, item);
});
}
});
function OutputData(tbody, item) {
tbody.append(
"<tr>" +
"<td style=\"border:1px solid #0094ff;\">" +
item.Id +
"</td>" +
"<td style=\"border:1px solid #0094ff;\">" + item.Name +
"</td>" +
"<td style=\"border:1px solid #0094ff;\">" + item.Age +
"</td>" + "</tr>");
}
}); </script>
</head>
<body>
<table>
<thead>
<tr>
<td style="border:1px solid #0094ff">Id</td>
<td style="border:1px solid #0094ff">Name</td>
<td style="border:1px solid #0094ff">Age</td> </tr>
</thead>
<tbody id="tbody1"> </tbody>
</table>
</body>
</html>

界面代码通过Ajax 获取API的值然后展示

最后效果如下:mvcAPI (入门 2)