前言:这里有一个项目,要求是在Student.mvc中调用Student.Api中控制器里的方法来实现一个表的查询。
如图:
第一步: 管理NuGet程序包
在Student.API 中添加 NuGet程序包
搜索 entity
搜索 cors
搜索json
第二步:配置
在WebApiConfig.cs文件中配置
//允许跨域的配置
// Web API 路由
config.MapHttpAttributeRoutes();
//允许跨域的配置
config.EnableCors(new EnableCorsAttribute("*","*","*"));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
在Global.asax文件中配置
//将返回的xml 设置为返回json数据
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
如图:
在Web.config文件中配置数据库连接字符串
<connectionStrings>
<add name="StudentDataModel1" connectionString="data source=.;initial catalog=Student;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
如图:
第三步:
在Student.DAL里的StudentDAL类里写查询表的方法
//查询出老师的信息
public static List<StudentInfo> GetTea()
{
List<StudentInfo> list = db.Database.SqlQuery<StudentInfo>("select * from StudentInfo where Pid=2").ToList();
return list;
}
如图:
在 Student.API里的 StudentController.cs(控制器文件)里调用Student.DAL里的StudentDAL类里写查询表的方法
[HttpGet]
public object SelTea()
{
List<Student.DAL.Entity.StudentInfo> list=Student.DAL.StudentDAL.GetTea();var data = new { Data = list };
return data ;
}
如图:
在Student.MVC 的View视图里写Ajax调用Student.API 里控制器
@{
ViewBag.Title = "SelTea";
Layout = null;
}<h2>老师信息</h2>
<table class="tab-content" id="tb_table">
<tr>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
<td>电话</td>
</tr>
<script id="Tea_data" type="text/x-jquery-tmpl">
{{each Data}}
<tr>
<td>${StudentName}</td>
<td>${StudentAge}</td>
<td>${StudentSex}</td>
<td>${StudentPhone}</td>
</tr>
{{/each}}
</script>
</table>
<script src="~/JS/jquery-1.8.2.min.js"></script>
<script src="~/JS/jquery.tmpl.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: "http://localhost:56443/api/Student",//api/控制器
type: "get",
//dataType: "json",
success: function (result) {
alert(result);
$("#Tea_data").tmpl(result).appendTo("#tb_table");
}
})
})
</script>
运行结果: