搭建三层,实现数据迁移
过程见之前的内容
在实现HTTP Cline链接API时要编写两个类用于显示
编写方法
-
添加
public int AddInfo(InfoModel info,Card card)
{
try
{
//往同时两个表添加数据
var userInfo = db.InfoModels.Add(info);
db.SaveChanges();
card.IId = userInfo.IId;
db.Cards.Add(card);
//事务(同时成功或成时失败)
return db.SaveChanges();
}
catch (Exception)
{
throw;
}
}
-
分页查询
public PageData<ViewModel> PageInfoShow(string iName,int? ci, int pageIndex=1,int pageSize=3)
{
//实例化类
PageData<ViewModel> pageData = new PageData<ViewModel>();
//Linq 查询
var query = from a in db.InfoModels
join b in db.Cards on a.IId equals b.IId
select new ViewModel
{
IId = a.IId,
Biaoqian = b.Biaoqian,
Ci = b.Ci,
Dengji = b.Dengji,
Fufei = b.Fufei,
ImgPath = a.ImgPath,
IName = a.IName,
Jifne = b.Jifne,
Money = b.Money,
Phone = a.Phone,
YuE = b.YuE
};
//拼接条件
if (!string.IsNullOrEmpty(iName))
{
query = query.Where(u => u.IName.Contains(iName));
}
if (ci!=null)
{
query = query.Where(u => u.Ci == ci);
}
//定义变量用于赋值
int count = query.Count();
//给类赋值
pageData.TotalCount = count;
pageData.TotalPage =Convert.ToInt32( Math.Ceiling(count * 1.0 / pageSize));
pageData.Data = query.OrderBy(u => u.IId).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
//返回类
return pageData;
}
API控制器
-
添加
[HttpPost]
public IHttpActionResult AddInfo([FromBody]InfoModel info)
{
try
{
return Json(bll.AddInfo(info, card));
}
catch (Exception)
{
throw;
}
}-
分页查询
[HttpGet]
public IHttpActionResult PageInfoShow([FromUri] string iName, int? ci, int pageIndex = 1, int pageSize = 3)
{
return Json(bll.PageInfoShow(iName, ci, pageIndex, pageSize));
}
-
MVC方法
-
可以先定义一个变量用于存储链接重复的部分
private const string BaseUrl = "http://localhost:54982/api/";
-
创建添加视图
public ActionResult AddInfoIndex()
{
return View();
} -
添加方法
[HttpPost]
public ActionResult AddInfo(InfoModel infoModel)
{
//实例化
HttpClient client = new HttpClient();
//赋值API地址
client.BaseAddress = new Uri(BaseUrl);
//完成调用WEBAPI AddUserInfo 的方法
var result = client.PostAsJsonAsync("AddUserInfo", infoModel).Result; //.Content.ReadAsStringAsync().Result;
//请求是否成功 成功 200
if (result.IsSuccessStatusCode)
{
var flag = result.Content.ReadAsStringAsync().Result;
if (Convert.ToInt32(flag) > 0)
{
return Content("<script>alert('添加成功')</script>");
}
else
{
return Content("<script>alert('添加失败')</script>");
}
}
else
{
return Content("<script>alert('HTTP响应失败')</script>");
}
} -