最近做了一个关于WebService+MVC跨域的增删改查,就写成了一个案例,用于和大家分享。
WebService项目截图如下:
Model层 用户实体类
商品信息表
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Model 8 { 9 public class Product //商品表 10 { 11 public int ProductId { get; set; } 12 public string ProductName { get; set; } 13 public string Kind { get; set; } 14 public string Color { get; set; } 15 public int StoreId { get; set; } 16 public string StoreName { get; set; } 17 public int StoreNum { get; set; } 18 public int WarningNum { get; set; } 19 } 20 }
商品仓库信息
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Model 8 { 9 public class Store 10 { 11 public int StoreId { get; set; } 12 public string StoreName { get; set; } 13 } 14 }
DAL层
存储过程实现分页功能
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Data.SqlClient; 7 using System.Data; 8 using Model; 9 namespace DAL 10 { 11 public class ProductDAL 12 { 13 /// <summary> 14 /// 登录 15 /// </summary> 16 /// <param name="userName"></param> 17 /// <param name="userPwd"></param> 18 /// <returns></returns> 19 public int CheckLogin(string userName, string userPwd) 20 { 21 //连接对象 22 SqlConnection sqlconn = new SqlConnection("Data Source =.; Initial Catalog = zonghefuxi; Integrated Security = True"); 23 //操作对象 24 var sqlcomm = new SqlCommand(); 25 //执行语句 26 sqlcomm.Connection = sqlconn; 27 sqlconn.Open(); 28 sqlcomm.CommandText = "sp_checkLogin";//指定存储过程名 29 sqlcomm.CommandType = System.Data.CommandType.StoredProcedure;//明确操作类型为存储过程 30 //用户名参数 31 var yonghuPar = new SqlParameter("@userName", SqlDbType.VarChar, 50); 32 yonghuPar.Value = userName; 33 //密码参数 34 var pwdPar = new SqlParameter("@userPwd", SqlDbType.VarChar, 50); 35 pwdPar.Value = userPwd; 36 //输出参数 结果 37 var result = new SqlParameter("@result", SqlDbType.Int); 38 result.Direction = ParameterDirection.Output;//指定为输出参数 39 40 sqlcomm.Parameters.Add(yonghuPar); 41 sqlcomm.Parameters.Add(pwdPar); 42 sqlcomm.Parameters.Add(result); 43 sqlcomm.ExecuteScalar(); 44 sqlconn.Close();//关闭数据库 45 //接收并返回结果 46 return Convert.ToInt32(result.Value); 47 } 48 /// <summary> 49 /// 查询分页 50 /// </summary> 51 /// <param name="pageindex"></param> 52 /// <param name="pagesize"></param> 53 /// <param name="pname"></param> 54 /// <param name="sid"></param> 55 /// <param name="pagecount"></param> 56 /// <returns></returns> 57 public DataTable GetProducts(int pageindex, int pagesize, string pname, int sid,ref int pagecount) 58 { 59 var sqlconn = new SqlConnection("Data Source =.; Initial Catalog = zonghefuxi; Integrated Security = True"); 60 var sqlcmd = new SqlCommand(); 61 sqlconn.Open(); 62 sqlcmd.Connection = sqlconn; 63 sqlcmd.CommandText = "sp_productpager"; 64 sqlcmd.CommandType = CommandType.StoredProcedure; 65 66 //页码参数 67 var pindex = new SqlParameter("@pageindex", SqlDbType.Int); 68 pindex.Value = pageindex; 69 //页面条数 70 var psize = new SqlParameter("@pagesize", SqlDbType.Int); 71 psize.Value = pagesize; 72 //商品名称 73 var proname = new SqlParameter("@ProName", SqlDbType.VarChar, 50); 74 proname.Value = pname; 75 //仓库编号 76 var storeid = new SqlParameter("@Sid", SqlDbType.Int); 77 storeid.Value = sid; 78 79 //一共多少页 输出参数 80 var pcount = new SqlParameter("@pagecount", SqlDbType.Int); 81 pcount.Direction = ParameterDirection.Output; 82 83 sqlcmd.Parameters.Add(pindex); 84 sqlcmd.Parameters.Add(psize); 85 sqlcmd.Parameters.Add(proname); 86 sqlcmd.Parameters.Add(storeid); 87 sqlcmd.Parameters.Add(pcount); 88 //结果datatable 89 DataTable dt = new DataTable(); 90 //适配器 91 SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlcmd); 92 dataAdapter.Fill(dt); 93 pagecount =Convert.ToInt32(pcount.Value);//一共几页返回给BLL 94 return dt; 95 } 96 //获取仓库信息 97 public DataTable GetStores() 98 { 99 return DBhelper.GetTable("select * from store"); 100 } 101 /// <summary> 102 /// 删除商品 103 /// </summary> 104 /// <param name="id"></param> 105 /// <returns></returns> 106 public int DelPro(int id) 107 { 108 string sql = "delete from storehistory where pid=" + id; 109 return DBhelper.ExecuteNonQuery(sql); 110 } 111 /// <summary> 112 /// 修改 113 /// </summary> 114 /// <param name="pro"></param> 115 /// <returns></returns> 116 public int UpdPro(Product pro) 117 { 118 string sql = string.Format("update storehistory set storeid={0},storenum={1},warningnum={2} where pid={3}", pro.StoreId, pro.StoreNum, pro.WarningNum, pro.ProductId); 119 120 return DBhelper.ExecuteNonQuery(sql); 121 } 122 /// <summary> 123 /// 根据商品id获取单个商品信息 124 /// </summary> 125 /// <param name="id"></param> 126 /// <returns></returns> 127 public DataTable GetProduct(int id) 128 { 129 string sql = @"select * from product p inner join storehistory s on 130 p.ProductID = s.PID where p.ProductID =" + id; 131 return DBhelper.GetTable(sql); 132 } 133 } 134 }
BLL业务逻辑层
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using DAL; 7 using System.Data; 8 using Model; 9 10 namespace BLL 11 { 12 public class ProductBLL 13 { 14 ProductDAL prod = new ProductDAL(); 15 /// <summary> 16 /// 登录 17 /// </summary> 18 /// <param name="userName"></param> 19 /// <param name="userPwd"></param> 20 /// <returns></returns> 21 public int CheckLogin(string userName, string userPwd) 22 { 23 return prod.CheckLogin(userName, userPwd); 24 } 25 /// <summary> 26 /// 查询分页 27 /// </summary> 28 /// <param name="pageindex"></param> 29 /// <param name="pagesize"></param> 30 /// <param name="pname"></param> 31 /// <param name="sid"></param> 32 /// <param name="pagecount"></param> 33 /// <returns></returns> 34 public DataTable GetProducts(int pageindex, int pagesize, string pname, int sid, ref int pagecount) 35 { 36 return prod.GetProducts(pageindex, pagesize, pname, sid, ref pagecount); 37 } 38 /// <summary> 39 /// 获取仓库信息 40 /// </summary> 41 /// <returns></returns> 42 public DataTable GetStores() 43 { 44 return prod.GetStores(); 45 } 46 /// <summary> 47 /// 删除商品信息 48 /// </summary> 49 /// <param name="id"></param> 50 /// <returns></returns> 51 public int DelPro(int id) 52 { 53 return prod.DelPro(id); 54 } 55 /// <summary> 56 /// 修改商品信息 57 /// </summary> 58 /// <param name="pro"></param> 59 /// <returns></returns> 60 public int UpdPro(Product pro) 61 { 62 return prod.UpdPro(pro); 63 } 64 /// <summary> 65 /// 根据商品Id获取单个商品信息 66 /// </summary> 67 /// <param name="id"></param> 68 /// <returns></returns> 69 public DataTable GetProduct(int id) 70 { 71 return prod.GetProduct(id); 72 } 73 } 74 }
WebFuXiService是使用WebService的项目
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Services; 6 using BLL; 7 using Model; 8 using System.Data; 9 using Newtonsoft.Json; 10 11 namespace WebFuXiService 12 { 13 /// <summary> 14 /// ProductService 的摘要说明 15 /// </summary> 16 [WebService(Namespace = "http://tempuri.org/")] 17 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 18 [System.ComponentModel.ToolboxItem(false)] 19 // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 20 // [System.Web.Script.Services.ScriptService] 21 public class ProductService : System.Web.Services.WebService 22 { 23 ProductBLL prob = new ProductBLL(); 24 [WebMethod] 25 public string CheckLogin(string uname, string upwd) 26 { 27 int result = prob.CheckLogin(uname, upwd); 28 if (result > 0) 29 { 30 return "登陆成功"; 31 } 32 else 33 { 34 return "用户名或密码错误"; 35 } 36 } 37 //获取商品信息 分页和查询 38 [WebMethod] 39 public List<Product> GetProducts(int pageindex, int pagesize, string pname, int sid, ref int clientCount) 40 { 41 int pagecount = 0; 42 DataTable dt = prob.GetProducts(pageindex, pagesize, pname, sid, ref pagecount); 43 clientCount = pagecount; 44 string jsonStr = JsonConvert.SerializeObject(dt); 45 var result = JsonConvert.DeserializeObject<List<Product>>(jsonStr); 46 47 return result; 48 } 49 /// <summary> 50 /// 显示仓库信息 51 /// 下拉列表信息 52 /// </summary> 53 /// <returns></returns> 54 [WebMethod] 55 public List<Store> GetStores() 56 { 57 DataTable dtStore = prob.GetStores(); 58 string jsonStr = JsonConvert.SerializeObject(dtStore); 59 List<Store> result = JsonConvert.DeserializeObject<List<Store>>(jsonStr); 60 return result; 61 } 62 /// <summary> 63 /// 删除 64 /// </summary> 65 /// <param name="id"></param> 66 /// <returns></returns> 67 [WebMethod] 68 public string DelPro(int id) 69 { 70 int result = prob.DelPro(id); 71 if (result > 0) 72 { 73 return "删除成功"; 74 } 75 else 76 { 77 return "删除失败"; 78 } 79 } 80 81 /// <summary> 82 /// 修改 83 /// </summary> 84 /// <param name="pro"></param> 85 /// <returns></returns> 86 [WebMethod] 87 public string UpdPro(Product pro) 88 { 89 int result = prob.UpdPro(pro); 90 if (result > 0) 91 { 92 return "修改成功"; 93 } 94 else 95 { 96 return "修改失败"; 97 } 98 } 99 100 /// <summary> 101 /// 根据id获取商品信息 102 /// </summary> 103 /// <param name="id"></param> 104 /// <returns></returns> 105 [WebMethod] 106 public Product GetProduct(int id) 107 { 108 DataTable dt = prob.GetProduct(id); 109 string json = JsonConvert.SerializeObject(dt);//json数组字符串[{'ProductId':2,'Name':'辣条'}] 110 List<Product> result = JsonConvert.DeserializeObject<List<Product>>(json); 111 return result.FirstOrDefault();//集合中单个的数据 112 } 113 } 114 }
MVC的项目截图如下:
从截图中我们可以看出需要引用一个服务引用,点击引用→点击添加服务引用→把地址输入到上面点击转到,然后点击确定就可以了。
WebProductCustom是一个MVC项目
控制器
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 using WebProductCustom.ServiceReference1; 7 using Newtonsoft.Json; 8 using WebProductCustom.Models; 9 10 namespace WebProductCustom.Controllers 11 { 12 public class ProductController : Controller 13 { 14 // GET: Product 15 [HttpGet] 16 public ActionResult Login() 17 { 18 19 return View(); 20 } 21 [HttpPost] 22 public ActionResult Login(string uname, string upwd) 23 { 24 ProductServiceSoapClient client = new ProductServiceSoapClient(); 25 string result = client.CheckLogin(uname, upwd); 26 return Content("<script>alert('" + result + "')</script>"); 27 } 28 /// <summary> 29 /// 显示查询方法 30 /// </summary> 31 /// <param name="pname"></param> 32 /// <param name="pcid"></param> 33 /// <returns></returns> 34 public ActionResult Show(string pname="",int pcid=-1) 35 { 36 ProductServiceSoapClient client = new ProductServiceSoapClient(); 37 client.GetStores(); 38 //下拉列表的绑定 39 ViewBag.Cks = client.GetStores(); 40 int count = 0; 41 Product[] products = client.GetProducts(1, 3, pname, pcid, ref count); 42 ViewBag.count = count; 43 ViewBag.cur = 1; 44 string jsonStr = JsonConvert.SerializeObject(products); 45 var result = JsonConvert.DeserializeObject<List<ProductViewModel>>(jsonStr); 46 return View(result); 47 } 48 /// <summary> 49 /// 分页 查询 50 /// </summary> 51 /// <param name="pageindex"></param> 52 /// <param name="pagesize"></param> 53 /// <param name="pname"></param> 54 /// <param name="pcid"></param> 55 /// <returns></returns> 56 public ActionResult PageHelper(int pageindex, int pagesize,string pname="",int pcid=-1) 57 { 58 ViewBag.cur = pageindex; //更新当前页码 59 ProductServiceSoapClient client = new ProductServiceSoapClient(); 60 ViewBag.Cks = client.GetStores(); 61 int count = 0; 62 Product[] products = client.GetProducts(pageindex, pagesize, pname, pcid, ref count); 63 ViewBag.count = count; //获取最后一页页码 64 string jsonStr = JsonConvert.SerializeObject(products); 65 var result = JsonConvert.DeserializeObject<List<ProductViewModel>>(jsonStr); 66 return View("Show", result);//查询到数据后交给Show视图显示 67 } 68 public ActionResult Delete(int id) 69 { 70 ProductServiceSoapClient client = new ProductServiceSoapClient(); 71 string result = client.DelPro(id); 72 return Content(result); 73 } 74 [HttpGet] 75 public ActionResult Edit(int id) 76 { 77 78 ProductServiceSoapClient client = new ProductServiceSoapClient(); 79 client.GetStores(); 80 ViewBag.Cks = client.GetStores();//下拉列表赋值 81 Product pro = client.GetProduct(id);//需要修改的商品 82 string jsonStr = JsonConvert.SerializeObject(pro); 83 ProductViewModel pv = JsonConvert.DeserializeObject<ProductViewModel>(jsonStr); 84 return View(pv); 85 } 86 [HttpPost] 87 public ActionResult Edit(ProductViewModel pro) 88 { 89 ProductServiceSoapClient client = new ProductServiceSoapClient(); 90 string jsonStr = JsonConvert.SerializeObject(pro); 91 Product product = JsonConvert.DeserializeObject<Product>(jsonStr); 92 string result = client.UpdPro(product); 93 return Content(result); 94 } 95 } 96 }
Models
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebProductCustom.Models { public class ProductViewModel { public int ProductId { get; set; } public string ProductName { get; set; } public string Kind { get; set; } public string Color { get; set; } public int StoreId { get; set; } public string StoreName { get; set; } public int StoreNum { get; set; } public int WarningNum { get; set; } } }
视图
1 @model IEnumerable<WebProductCustom.Models.ProductViewModel> 2 @{ 3 Layout = null; 4 } 5 6 <!DOCTYPE html> 7 8 <html> 9 <head> 10 <meta name="viewport" content="width=device-width" /> 11 <title>Show</title> 12 <link href="~/Content/bootstrap.css" rel="stylesheet" /> 13 <script src="~/Scripts/jquery-1.10.2.js"></script> 14 </head> 15 <body> 16 <div> 17 @using (Html.BeginForm()) 18 { 19 <span>商品名称</span><input id="Text1" type="text" name="pname" /> 20 <span>商品仓库</span> 21 <select id="Select1" name="pcid"> 22 <option value="-1">请选择仓库</option> 23 @foreach (var item in ViewBag.Cks) 24 { 25 <option value="@item.StoreId">@item.StoreName</option> 26 } 27 </select> 28 <input id="Submit1" type="submit" value="查询" class="btn btn-primary" /> 29 } 30 <table class="table table-bordered"> 31 <tr> 32 <th>商品编号</th> 33 <th>商品名称</th> 34 <th>仓库名称</th> 35 <th>库存数量</th> 36 <th>预警数量</th> 37 <th>操作</th> 38 </tr> 39 @foreach (var item in Model) 40 { 41 <tr> 42 <td>@item.ProductId</td> 43 <td>@item.ProductName</td> 44 <td>@item.StoreName</td> 45 <td>@item.StoreNum</td> 46 <td>@item.WarningNum</td> 47 <td> 48 @Html.ActionLink("修改", "Edit", new { id = item.ProductId }) 49 @Html.ActionLink("删除", "Delete", new { id = item.ProductId }) 50 </td> 51 </tr> 52 } 53 </table> 54 <input id="hidIndex" type="hidden" value="@ViewBag.cur" /> 55 <input id="Button1" type="button" value="首页" onclick="FirstPage()" /> 56 <input id="Button1" type="button" value="上一页" onclick="UpPage()" /> 57 <input id="Button1" type="button" value="下一页" onclick="DownPage()" /> 58 <input id="Last" type="button" value="尾页" class="@ViewBag.Count" onclick="LastPage()" /> 59 </div> 60 <script> 61 function FirstPage() { 62 location.href = "/Product/PageHelper?pageindex=1&pagesize=3"; 63 } 64 function DownPage() { 65 var curPageIndex = $('#hidIndex').val(); 66 var pageindex = Number(curPageIndex) + 1;//获取需要访问的页码 67 $('#hidIndex').val(pageindex);//更新当前页码 68 location.href = "/Product/PageHelper?pageindex=" + pageindex + "&pagesize=3"; 69 } 70 function UpPage() { 71 var curPageIndex = $('#hidIndex').val(); 72 var pageindex = Number(curPageIndex) - 1;//获取需要访问的页码 73 $('#hidIndex').val(pageindex);//更新当前页码 74 location.href = "/Product/PageHelper?pageindex=" + pageindex + "&pagesize=3"; 75 } 76 function LastPage() { 77 var lastNum = $('#Last').prop('class');//最后一页页码 78 location.href = "/Product/PageHelper?pageindex=" + lastNum + "&pagesize=3"; 79 } 80 </script> 81 </body> 82 </html>
1 @{ 2 Layout = null; 3 } 4 5 <!DOCTYPE html> 6 7 <html> 8 <head> 9 <meta name="viewport" content="width=device-width" /> 10 <title>Login</title> 11 <link href="~/Content/bootstrap.css" rel="stylesheet" /> 12 </head> 13 <body> 14 <div> 15 @using (Html.BeginForm()) 16 { 17 18 19 <table class="table table-bordered"> 20 <tr> 21 <td>用户名</td> 22 <td><input id="Text1" name="uname" type="text" /></td> 23 </tr> 24 <tr> 25 <td>密码</td> 26 <td><input id="Password1" name="upwd" type="password" /></td> 27 </tr> 28 <tr> 29 <td></td> 30 <td><input id="Submit1" type="submit" value="登陆" class="btn btn-primary" /></td> 31 </tr> 32 </table> 33 } 34 </div> 35 </body> 36 </html>
1 @model WebProductCustom.Models.ProductViewModel 2 3 @{ 4 Layout = null; 5 } 6 7 <!DOCTYPE html> 8 9 <html> 10 <head> 11 <meta name="viewport" content="width=device-width" /> 12 <title>Edit</title> 13 <script src="~/Scripts/jquery-1.10.2.js"></script> 14 <script src="~/Scripts/jquery.validate.js"></script> 15 <script src="~/Scripts/jquery.validate.unobtrusive.js"></script> 16 </head> 17 <body> 18 @using (Html.BeginForm()) 19 { 20 @Html.AntiForgeryToken() 21 22 <div class="form-horizontal"> 23 <h4>编辑商品</h4> 24 <hr /> 25 @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 26 <div class="form-group"> 27 @Html.LabelFor(model => model.ProductId, htmlAttributes: new { @class = "control-label col-md-2" }) 28 <div class="col-md-10"> 29 @Html.EditorFor(model => model.ProductId, new { htmlAttributes = new { @class = "form-control" } }) 30 @Html.ValidationMessageFor(model => model.ProductId, "", new { @class = "text-danger" }) 31 </div> 32 </div> 33 34 <div class="form-group"> 35 @Html.LabelFor(model => model.ProductName, htmlAttributes: new { @class = "control-label col-md-2" }) 36 <div class="col-md-10"> 37 @Html.EditorFor(model => model.ProductName, new { htmlAttributes = new { @class = "form-control" } }) 38 @Html.ValidationMessageFor(model => model.ProductName, "", new { @class = "text-danger" }) 39 </div> 40 </div> 41 42 <div class="form-group"> 43 @Html.LabelFor(model => model.Kind, htmlAttributes: new { @class = "control-label col-md-2" }) 44 <div class="col-md-10"> 45 @Html.EditorFor(model => model.Kind, new { htmlAttributes = new { @class = "form-control" } }) 46 @Html.ValidationMessageFor(model => model.Kind, "", new { @class = "text-danger" }) 47 </div> 48 </div> 49 50 <div class="form-group"> 51 @Html.LabelFor(model => model.Color, htmlAttributes: new { @class = "control-label col-md-2" }) 52 <div class="col-md-10"> 53 @Html.EditorFor(model => model.Color, new { htmlAttributes = new { @class = "form-control" } }) 54 @Html.ValidationMessageFor(model => model.Color, "", new { @class = "text-danger" }) 55 </div> 56 </div> 57 58 <div class="form-group"> 59 @Html.LabelFor(model => model.StoreId, htmlAttributes: new { @class = "control-label col-md-2" }) 60 <div class="col-md-10"> 61 <select id="Select1" name="StoreId"> 62 <option value="-1">请选择仓库</option> 63 @foreach (var item in ViewBag.Cks) 64 { 65 <option value="@item.StoreId" @if (item.StoreId == Model.StoreId) { @: selected 66 }> 67 @item.StoreName 68 </option> 69 } 70 </select> 71 </div> 72 </div> 73 74 75 <div class="form-group"> 76 @Html.LabelFor(model => model.StoreNum, htmlAttributes: new { @class = "control-label col-md-2" }) 77 <div class="col-md-10"> 78 @Html.EditorFor(model => model.StoreNum, new { htmlAttributes = new { @class = "form-control" } }) 79 @Html.ValidationMessageFor(model => model.StoreNum, "", new { @class = "text-danger" }) 80 </div> 81 </div> 82 83 <div class="form-group"> 84 @Html.LabelFor(model => model.WarningNum, htmlAttributes: new { @class = "control-label col-md-2" }) 85 <div class="col-md-10"> 86 @Html.EditorFor(model => model.WarningNum, new { htmlAttributes = new { @class = "form-control" } }) 87 @Html.ValidationMessageFor(model => model.WarningNum, "", new { @class = "text-danger" }) 88 </div> 89 </div> 90 91 <div class="form-group"> 92 <div class="col-md-offset-2 col-md-10"> 93 <input type="submit" value="提交" class="btn btn-default" /> 94 </div> 95 </div> 96 </div> 97 } 98 99 <div> 100 @Html.ActionLink("Back to List", "Index") 101 </div> 102 </body> 103 </html>
Web.config
还没有确定在
<system.webServer> <validation validateIntegratedModeConfiguration="false" />//有没有不确定 </system.webServer>
源码下载: