微信小程序支付之c,微信小程序服务端获取用户

2019-06-07 作者:web前端   |   浏览(186)

微信小程序支付c#后台完成

 C#微信小程序服务端获取用户解密消息实例代码

一, NVelocity 是 一般管理程序.ashx 和 前台页面模板的大桥。 

明天为我们带来比较轻巧的支付后台管理

福寿康宁代码:

二,大家以后创设1个大概的询问:  

先是下载官方的c#模板(WxPayAPI),将模板(WxPayAPI)增加到服务器上,然后在WxPayAPI项目目录中加多多个“一般管理程序” (改名称为GetOpenid.ashx、pay.ashx)

using AIOWeb.Models; 
using Newtonsoft.Json; 
using Newtonsoft.Json.Linq; 
using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Data.SqlClient; 
using System.Linq; 
using System.Web; 

namespace AIOWeb 
{ 
  /// <summary> 
  /// wxapi 的摘要说明 
  /// </summary> 
  public class wxapi : IHttpHandler 
  { 
    public void ProcessRequest(HttpContext context) 
    { 
      context.Response.ContentType = "text/plain"; 

      string code = ""; 
      string iv = ""; 
      string encryptedData = ""; 
      try 
      { 
        code = HttpContext.Current.Request.QueryString["code"].ToString(); 
        iv = HttpContext.Current.Request.QueryString["iv"].ToString(); 
        encryptedData = HttpContext.Current.Request.QueryString["encryptedData"].ToString(); 
      } 
      catch (Exception ex) 
      { 
        context.Response.Write(ex.ToString()); 
      } 

      string Appid = "wxdb2641f85b04f1b3"; 
      string Secret = "8591d8cd7197b9197e17b3275329a1e7"; 
      string grant_type = "authorization_code"; 

      //向微信服务端 使用登录凭证 code 获取 session_key 和 openid  
      string url = "https://api.weixin.qq.com/sns/jscode2session?appid="   Appid   "&secret="   Secret   "&js_code="   code   "&grant_type="   grant_type; 
      string type = "utf-8"; 

      AIOWeb.Models.GetUsersHelper GetUsersHelper = new AIOWeb.Models.GetUsersHelper(); 
      string j = GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串 

      //将字符串转换为json格式 
      JObject jo = (JObject)JsonConvert.DeserializeObject(j); 

      result res = new result(); 
      try 
      { 
        //微信服务器验证成功 
        res.openid = jo["openid"].ToString(); 
        res.session_key = jo["session_key"].ToString(); 
      } 
      catch (Exception) 
      { 
        //微信服务器验证失败 
        res.errcode = jo["errcode"].ToString(); 
        res.errmsg = jo["errmsg"].ToString(); 
      } 
      if (!string.IsNullOrEmpty(res.openid)) 
      { 
        //用户数据解密 
        GetUsersHelper.AesIV = iv; 
        GetUsersHelper.AesKey = res.session_key; 

        string result = GetUsersHelper.AESDecrypt(encryptedData); 


        //存储用户数据 
        JObject _usrInfo = (JObject)JsonConvert.DeserializeObject(result); 

        userInfo userInfo = new userInfo(); 
        userInfo.openId = _usrInfo["openId"].ToString(); 

        try //部分验证返回值中没有unionId 
        { 
          userInfo.unionId = _usrInfo["unionId"].ToString(); 
        } 
        catch (Exception) 
        { 
          userInfo.unionId = "unionId"; 
        } 

        userInfo.nickName = _usrInfo["nickName"].ToString(); 
        userInfo.gender = _usrInfo["gender"].ToString(); 
        userInfo.city = _usrInfo["city"].ToString(); 
        userInfo.province = _usrInfo["province"].ToString(); 
        userInfo.country = _usrInfo["country"].ToString(); 
        userInfo.avatarUrl = _usrInfo["avatarUrl"].ToString(); 

        object watermark = _usrInfo["watermark"].ToString(); 
        object appid = _usrInfo["watermark"]["appid"].ToString(); 
        object timestamp = _usrInfo["watermark"]["timestamp"].ToString(); 


        #region 


        //创建连接池对象(与数据库服务器进行连接) 
        SqlConnection conn = new SqlConnection("server=127.0.0.1;database=Test;uid=sa;pwd=1"); 
        //打开连接池 
        conn.Open(); 
        //创建命令对象 
        string Qrystr = "SELECT * FROM WeChatUsers WHERE openId='"   userInfo.openId   "'"; 
        SqlCommand cmdQry = new SqlCommand(Qrystr, conn); 
        object obj = cmdQry.ExecuteScalar(); 
        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) 
        { 
          string str = "INSERT INTO WeChatUsers ([UnionId] ,[OpenId],[NickName],[Gender],[City],[Province],[Country],[AvatarUrl],[Appid],[Timestamp],[Memo],[counts])VALUES('"   userInfo.unionId   "','"   userInfo.openId   "','"   userInfo.nickName   "','"   userInfo.gender   "','"   userInfo.city   "','"   userInfo.province   "','"   userInfo.country   "','"   userInfo.avatarUrl   "','"   appid.ToString()   "','"   timestamp.ToString()   "','来自微信小程序','1')"; 

          SqlCommand cmdUp = new SqlCommand(str, conn); 
          // 执行操作 
          try 
          { 
            int row = cmdUp.ExecuteNonQuery(); 
          } 
          catch (Exception ex) 
          { 
            context.Response.Write(ex.ToString()); 
          } 
        } 
        else 
        { 
          //多次访问,记录访问次数counts  更新unionId是预防最初没有,后期关联后却仍未记录 
          string str = "UPDATE dbo.WeChatUsers SET counts = counts 1,UnionId = '"   userInfo.unionId   "' WHERE OpenId='"   userInfo.openId   "'"; 
          SqlCommand cmdUp = new SqlCommand(str, conn); 
          int row = cmdUp.ExecuteNonQuery(); 
        } 

        //关闭连接池 
        conn.Close(); 
        #endregion 

        //返回解密后的用户数据 
        context.Response.Write(result); 
      } 
      else 
      { 
        context.Response.Write(j); 
      } 
    } 

    public bool IsReusable 
    { 
      get 
      { 
        return false; 
      } 
    } 
  } 
} 

    A,新建项目,把NVelocity.dll拉入项目中,并加上对其引用

之后展开business目录下的JsApiPay.cs,在JsApiPay.cs中期维修改如下两处

GetUsersHelper 帮助类

  web前端 1

web前端 2

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Security.Cryptography; 
using System.Text; 
using System.Threading.Tasks; 

namespace AIOWeb.Models 
{ 
  public class GetUsersHelper 
  { 

    /// <summary> 
    /// 获取链接返回数据 
    /// </summary> 
    /// <param name="Url">链接</param> 
    /// <param name="type">请求类型</param> 
    /// <returns></returns> 
    public string GetUrltoHtml(string Url, string type) 
    { 
      try 
      { 
        System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url); 
        // Get the response instance. 
        System.Net.WebResponse wResp = wReq.GetResponse(); 
        System.IO.Stream respStream = wResp.GetResponseStream(); 
        // Dim reader As StreamReader = New StreamReader(respStream) 
        using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type))) 
        { 
          return reader.ReadToEnd(); 
        } 
      } 
      catch (System.Exception ex) 
      { 
        return ex.Message; 
      } 
    } 
    #region 微信小程序用户数据解密 

    public static string AesKey; 
    public static string AesIV; 

    /// <summary> 
    /// AES解密 
    /// </summary> 
    /// <param name="inputdata">输入的数据encryptedData</param> 
    /// <param name="AesKey">key</param> 
    /// <param name="AesIV">向量128</param> 
    /// <returns name="result">解密后的字符串</returns> 
    public string AESDecrypt(string inputdata) 
    { 
      try 
      { 
        AesIV = AesIV.Replace(" ", " "); 
        AesKey = AesKey.Replace(" ", " "); 
        inputdata = inputdata.Replace(" ", " "); 
        byte[] encryptedData = Convert.FromBase64String(inputdata); 

        RijndaelManaged rijndaelCipher = new RijndaelManaged(); 
        rijndaelCipher.Key = Convert.FromBase64String(AesKey); // Encoding.UTF8.GetBytes(AesKey); 
        rijndaelCipher.IV = Convert.FromBase64String(AesIV);// Encoding.UTF8.GetBytes(AesIV); 
        rijndaelCipher.Mode = CipherMode.CBC; 
        rijndaelCipher.Padding = PaddingMode.PKCS7; 
        ICryptoTransform transform = rijndaelCipher.CreateDecryptor(); 
        byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length); 
        string result = Encoding.UTF8.GetString(plainText); 

        return result; 
      } 
      catch (Exception) 
      { 
        return null; 

      } 
    } 
    #endregion 
  } 
} 

  B,新建Common_Nvelocity.cs类, 借助NVelocity模板引擎把数据Data传递给相应的TemplateName页面

接下来在GetOpenid.ashx中参与代码如下:

感激阅读,希望能扶助到我们,谢谢大家对本站的支撑!

web前端 3web前端 4

public class GetOpenid : IHttpHandler 
  { 
    public string openid { get; set; } 

    public void ProcessRequest(HttpContext context) 
    { 

      string code = HttpContext.Current.Request.QueryString["code"]; 
      WxPayData data = new WxPayData(); 
      data.SetValue("appid", WxPayConfig.APPID); 
      data.SetValue("secret", WxPayConfig.APPSECRET); 
      data.SetValue("code", code); 
      data.SetValue("grant_type", "authorization_code"); 
      string url = "https://api.weixin.qq.com/sns/oauth2/access_token?"   data.ToUrl(); 

      //请求url以获取数据 
      string result = HttpService.Get(url); 

      Log.Debug(this.GetType().ToString(), "GetOpenidAndAccessTokenFromCode response : "   result); 

      //保存access_token,用于收货地址获取 
      JsonData jd = JsonMapper.ToObject(result); 
      //access_token = (string)jd["access_token"]; 

      //获取用户openid 
      openid = (string)jd["openid"]; 
      context.Response.Write(openid);//获取H5调起JS API参数 

    }

您或然感兴趣的稿子:

  • 微信小程序支付之c#后台达成格局
  • C#付出之微信小程序发送模板音讯功效
  • 微信小程序支付C#后端源码
using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Runtime;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace CIUD_NVelocitySample
{
    public class Common_Nvelocity
    {

        /// <summary>
        /// 通过NVelocity模板引擎,把Data数据参数中的数据传递到Template模板中
        /// </summary>
        /// <param name="TemplateName">模板页面名称</param>
        /// <param name="Data">参数数据</param>
        /// <returns>返回HTML直接渲染生成 页面</returns>
        public static string Template_Nvelocity(string TemplateName, object Data)
        {

            //创建NVlecocity模板引擎的实例对象
            VelocityEngine vlEngine = new VelocityEngine();

            //初始化实例对象,定义对象的部分属性
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");//声明模板是在file中
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/Templates"));  //指定模板文件所在文件夹
            vlEngine.Init(props);

            //替换模板中的数据
            VelocityContext vltContext = new VelocityContext();
            vltContext.Put("data", Data);  //设置参数,在HTML模板中可以通过$Data读取数据


            //从文件中读取模板
            Template VltTemp = vlEngine.GetTemplate(TemplateName);
            //合并模板
            StringWriter writer = new StringWriter();
            VltTemp.Merge(vltContext, writer);

            //转化为字符串
            string html = writer.GetStringBuilder().ToString();

            return html;
        }
    }
}

在pay.ashx中投入代码如下:

View Code

public class pay : IHttpHandler 
  { 

    public void ProcessRequest(HttpContext context) 
    {        
      context.Response.ContentType = "text/plain"; 

      string openid = HttpContext.Current.Request.QueryString["openid"]; 
      string total_fee = HttpContext.Current.Request.QueryString["total_fee"]; 
      JsApiPay jsApiPay = new JsApiPay(context); 
      jsApiPay.openid = openid; 
      jsApiPay.total_fee = int.Parse(total_fee); 
      WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(); 
      context.Response.Write(jsApiPay.GetJsApiParameters());//获取H5调起JS API参数 
    }

  C,新建SQLHelper.cs类,从数据库中读写多少:

 然后发布就足以了(记得将有关的消息appid等填好)

web前端 5web前端 6

 微信小程序的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


namespace CIUD_NVelocitySample
{

    public class SQLHelper
    {
        SqlConnection sqlConn = null;
        SqlCommand sqlCom = null;
        SqlDataReader sdr = null;
        public SQLHelper()
        {

        }
        private SqlConnection getConn()
        {
            string connStr = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
            if (sqlConn == null)
            {
                sqlConn = new SqlConnection(connStr);
                sqlConn.Open();

            }
            if (sqlConn.State == ConnectionState.Closed)
            {
                sqlConn.Open();
            }
            return sqlConn;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="ct"></param>
        /// <returns></returns>
        public int ExecuteNonQuery(string strSql, CommandType ct)
        {
            int res = 0;
            try
            {
                sqlCom = new SqlCommand(strSql, getConn());
                sqlCom.CommandType = ct;
                res = (int)sqlCom.ExecuteNonQuery();

            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                {
                    sqlConn.Close();
                }
            }
            return res;
        }
        public int ExecuteNonQuery(string strSql, SqlParameter[] sqlPara, CommandType ct)
        {

            int res = 0;
            try
            {
                sqlCom = new SqlCommand(strSql, getConn());
                sqlCom.CommandType = ct;
                sqlCom.Parameters.AddRange(sqlPara);
                res = (int)sqlCom.ExecuteNonQuery();
                sqlCom.Parameters.Clear();
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                {
                    sqlConn.Close();
                }
            }
            return res;
        }
        public object ExecuteScalar(string strSql, CommandType ct)
        {
            object obj;
            try
            {
                sqlCom = new SqlCommand(strSql, getConn());
                sqlCom.CommandType = ct;
                obj = sqlCom.ExecuteScalar();
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                {
                    sqlConn.Close();
                }
            }
            return obj;
        }
        public object ExecuteScalar(string strSql, SqlParameter[] sqlPara, CommandType ct)
        {
            object obj;
            try
            {
                sqlCom = new SqlCommand(strSql, getConn());
                sqlCom.CommandType = ct;
                sqlCom.Parameters.AddRange(sqlPara);
                obj = sqlCom.ExecuteScalar();
                sqlCom.Parameters.Clear();
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                {
                    sqlConn.Close();
                }
            }
            return obj;
        }
        public SqlDataReader ExecuteReader(string strSql, CommandType ct)
        {

            try
            {
                sqlCom = new SqlCommand(strSql, getConn());
                sqlCom.CommandType = ct;
                using (sdr = sqlCom.ExecuteReader(CommandBehavior.CloseConnection)) { }//释放sdr所占的资源
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                {
                    sqlConn.Close();
                }
            }
            return sdr;
        }
        public SqlDataReader ExecuteReader(string strSql, SqlParameter[] sqlPara, CommandType ct)
        {

            try
            {
                sqlCom = new SqlCommand(strSql, getConn());
                sqlCom.CommandType = ct;
                sqlCom.Parameters.AddRange(sqlPara);
                using (sdr = sqlCom.ExecuteReader(CommandBehavior.CloseConnection)) { }
                sqlCom.Parameters.Clear();
            }
            catch (Exception ex)
            {
                throw ex;

            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                {
                    sqlConn.Close();
                }
            }
            return sdr;
        }
        public DataTable ExecuteQuery(string strSql, CommandType ct)
        {
            DataTable dt;
            try
            {
                dt = new DataTable();
                sqlCom = new SqlCommand(strSql, getConn());
                sqlCom.CommandType = ct;
                using (sdr = sqlCom.ExecuteReader(CommandBehavior.CloseConnection)) { dt.Load(sdr); }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                {
                    sqlConn.Close();
                }
            }
            return dt;
        }
        public DataTable ExecuteQuery(string strSql, SqlParameter[] sqlPara, CommandType ct)
        {
            DataTable dt;
            try
            {
                dt = new DataTable();
                sqlCom = new SqlCommand(strSql, getConn());
                sqlCom.CommandType = ct;
                sqlCom.Parameters.AddRange(sqlPara);
                using (sdr = sqlCom.ExecuteReader(CommandBehavior.CloseConnection))
                { dt.Load(sdr); }
                sqlCom.Parameters.Clear();

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                {
                    sqlConn.Close();
                }
            }
            return dt;
        }
    }
}
wxpay: function () { 
  var that = this 
  //登陆获取code 
  wx.login({ 
   success: function (res) { 
    console.log(res.code) 
    //获取openid 
    that.getOpenId(res.code) 
   } 
  }); 
 }, 
 getOpenId: function (code) { 
//获取openID 

  var that = this; 
  wx.request({ 
   url: 'http://*******/WxPayAPI/GetOpenid.ashx?code='  code , //改为自己的域名
   data: {}, 
  // method: 'GET', 
   success: function (res) { 
   var a12=res.data 
   that.generateOrder(a12) 
   //console.log(a12) 
   }, 
   fail: function () { 
    // fail 
   }, 
   complete: function () { 
    // complete 
   } 
  }) 
 }, 
/**生成商户订单 */ 
 generateOrder: function (openid) { 
  var that = this; 
  //console.log(openid) 
  //统一支付 
  wx.request({ 
   url: 'http://*******/WxPayAPI/pay.ashx', //改为自己的域名
   //method: 'GET', 
   data: { 
    total_fee: 1,//1分 
    openid: openid, 
   }, 
   header: { 
    'content-type': 'application/json' 
   }, 

   success: function (res) { 

    var pay = res.data 
    //发起支付 

    var timeStamp = pay.timeStamp; 
    var packages = pay.package; 
    var paySign = pay.paySign; 
    var nonceStr = pay.nonceStr; 
    var param = { "timeStamp": timeStamp, "package": packages, "paySign": paySign, "signType": "MD5", "nonceStr": nonceStr }; 

    that.pay(param) 
   }, 
  }) 
 }, 

 /* 支付  */ 
 pay: function (param) { 

  wx.requestPayment({ 
   timeStamp: param.timeStamp, 
   nonceStr: param.nonceStr, 
   package: param.package, 
   signType: param.signType, 
   paySign: param.paySign, 
   success: function (res) { 
    // success 

    wx.navigateBack({ 
     delta: 1, // 回退前 delta(默认为1) 页面 
     success: function (res1) { 
      wx.showToast({ 
       title: '支付成功', 
       icon: 'success', 
       duration: 2000 
      }); 

     }, 
     fail: function () { 
      // fail 

     }, 
     complete: function () { 

     } 
    }) 
   }, 
   fail: function (res) { 
    // fail 
   }, 
   complete: function () { 
    // complete 
   } 
  }) 
 }, 

View Code

如有疑问请留言大概到本站社区调换座谈,谢谢阅读,希望能协助到大家,多谢大家对本站的支撑!

  D,数据库中新建NVelocity_Sample数据库增添表T_Person,自个儿增添几条测试数据:

您大概感兴趣的稿子:

  • C#开辟之微信小程序发送模板音讯成效
  • C#微信小程序服务端获取用户解密新闻实例代码
  • 微信小程序支付C#后端源码

web前端 7web前端 8

USE [NVelocity_Sample]
GO

/****** Object:  Table [dbo].[T_Person]    Script Date: 2015/5/13 22:07:39 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[T_Person](
    [ID] [decimal](18, 0) IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
    [Email] [nvarchar](250) NOT NULL,
 CONSTRAINT [PK_T_Person] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

View Code

  E. WebConfig增添连接字符串:

web前端 9web前端 10

<?xml version="1.0" encoding="utf-8"?>

<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.0" />
    </system.web>
  <connectionStrings>
    <add name="connString" connectionString="Data Source=.; Initial Catalog=NVelocity_Sample; User Id=sa; Password=123456"/>
  </connectionStrings>
</configuration>

View Code

  以上完结大旨设置,上面大家 增多.ashx和html模板页面

  F, 增加PersonList.ashx 一般管理程序,从数据库中读取数据

web前端 11web前端 12

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

namespace CIUD_NVelocitySample
{
    /// <summary>
    /// PersonList 的摘要说明
    /// </summary>
    public class PersonList : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";

            //调用SQLHelper查询数据
            SQLHelper sqlH = new SQLHelper();
            DataTable dt = sqlH.ExecuteQuery("SELECT  [ID],[Name],[Email] FROM [NVelocity_Sample].[dbo].[T_Person]", CommandType.Text);  //读取T_Person中的数据

            //Rows属性,代表表格中数据行的集合(DataRow集合)
            //传递DataRowCollection给模板,方便遍历
            string strHtml = Common_Nvelocity.Template_Nvelocity("PersonList.html", dt.Rows);

            context.Response.Write(strHtml);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

View Code

  G, 增多坦普尔文件夹,并在文件夹中加多PersonList.html模板文件

web前端 13web前端 14

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>人员列表</title>
</head>
<body>
    <ul>
        #foreach($d in $data)
        <li>姓名:$d.Name &nbsp; 邮箱:$d.email</li>
        #end
    </ul>
</body>
</html>

View Code

  H, 运转程序后显得如下:

  web前端 15

  以上达成查询效率!

 三,实现Insert成效, 我们一直在PersonAdd页面包车型客车中增加文本框达成 Insert 功效

  A.在PersonAdd.html中增加 Form用于提交数据

web前端 16web前端 17

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form action="PersonAdd.ashx" method="get">
        姓名:
        <input type="text" name="PersonName" />
        <br />
        邮箱:<input type="email" name="Email" />
        <input type="submit" value="新增" />
    </form>
    <ul>
        #foreach($d in $data)
        <li>姓名:$d.Name &nbsp; 邮箱:$d.email&nbsp; <a href="PersonEdit.ashx?ID=$d.ID&Name=$d.Name&Email=$d.email">编辑</a></li>
        #end
    </ul>
</body>
</html>

View Code

  B. 点击Button提交数据今后,把Form表单中的数据提交到PersonAdd.ashx页面,假诺文本框中的内容不为空则写入数据库

web前端 18web前端 19

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

namespace CIUD_NVelocitySample
{
    /// <summary>
    /// PersonAdd 的摘要说明
    /// </summary>
    public class PersonAdd : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            string strPersonName = context.Request.QueryString["PersonName"];
            string strEmail = context.Request.QueryString["Email"];
            SQLHelper sqlH = new SQLHelper();
            if (string.IsNullOrEmpty(strPersonName) == false && string.IsNullOrEmpty(strEmail) == false)
            {
                int numSucc = 0;
                //Insert
                numSucc = sqlH.ExecuteNonQuery("insert into [NVelocity_Sample].[dbo].[T_Person]([Name],[Email]) values('"   strPersonName   "','"   strEmail   "')", CommandType.Text);
            }


            //写入数据之后再读取出来,传递到模板页面
            //调用SQLHelper查询数据
            DataTable dt = sqlH.ExecuteQuery("SELECT  [ID],[Name],[Email] FROM [NVelocity_Sample].[dbo].[T_Person]", CommandType.Text);  //读取T_Person中的数据
            //Rows属性,代表表格中数据行的集合(DataRow集合)
            //传递DataRowCollection给模板,方便遍历
            string strHtml = Common_Nvelocity.Template_Nvelocity("PersonAdd.html", dt.Rows);


            context.Response.Write(strHtml);

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

View Code

  达成效益:  

  web前端 20

肆,落成艾德it编辑功用,大家抬高对应的Person艾德it.html和Person艾德it.ashx页面  来管理编辑。

  PersonAdd页面中显得列表的末尾增多 “编辑” 超链接把数据传递到 PersonEdit.ashx页面中张开编辑管理:

  A. PersonAdd.html 的PersonList后添加 “编辑” 超链接:

web前端 21web前端 22

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form action="PersonAdd.ashx" method="get">
        姓名:
        <input type="text" name="PersonName" />
        <br />
        邮箱:<input type="email" name="Email" />
        <input type="submit" value="新增" />
    </form>
    <ul>
        #foreach($d in $data)
        <li>姓名:$d.Name &nbsp; 邮箱:$d.email&nbsp; <a href="PersonEdit.ashx?ID=$d.ID&Name=$d.Name&Email=$d.email">编辑</a></li>
        #end
    </ul>
</body>
</html>

View Code

  B.新扩展 Person艾德it.html模板页面和Person艾德it.ashx一般管理程序页面

web前端 23web前端 24

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form action="PersonEdit.ashx" method="get">
        序号:<input type="text" name="ID" value="$data.ID" />
        姓名:
        <input type="text" name="Name" value="$data.Name" />
        <br />
        邮箱:<input type="email" name="Email" value="$data.Email" />
        <br />
        <input type="submit" value="保存" />
    </form>
</body>
</html>

View Code

web前端 25web前端 26

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

namespace CIUD_NVelocitySample
{
    /// <summary>
    /// PersonEdit 的摘要说明
    /// </summary>
    public class PersonEdit : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            string strID = context.Request.QueryString["ID"];
            string strPersonName = context.Request.QueryString["Name"];
            string strEmail = context.Request.QueryString["Email"];
            string strFromPage = context.Request.UrlReferrer.ToString();
            SQLHelper sqlH = new SQLHelper();
            string strHtml = "";

            //判断URL参数来源 哪个页面
            //如果来自: PersonAdd.ashx 页面,则是点击了“编辑”进入编辑页面,此时需要  显示页面内容
            if (strFromPage.ToLower().Contains("personadd.ashx"))
            {
                var Data = new { ID = strID, Name = strPersonName, Email = strEmail };
                strHtml = Common_Nvelocity.Template_Nvelocity("PersonEdit.html", Data);
            }
            //如果来自: PersonEdit.html页面,则是点击 PersonEdit.html 页面的保存按钮,此时需要把数据更新到数据库后,返回到PersonAdd.html
            else if (strFromPage.ToLower().Contains("personedit.ashx"))
            {
                if (string.IsNullOrEmpty(strPersonName) == false && string.IsNullOrEmpty(strEmail) == false)
                {
                    int numSucc = 0;
                    //Insert
                    numSucc = sqlH.ExecuteNonQuery("  update [NVelocity_Sample].[dbo].[T_Person] set [Name]='"   strPersonName   "', [Email]='"   strEmail   "' where [ID]='"   strID   "'", CommandType.Text);
                    if (numSucc == 1)
                    {
                       //更新成功,跳转到 PersonAdd.ashx页面
                        context.Response.Redirect("personadd.ashx");
                    }
                    else
                    {   //加载失败,依旧显示 PersonEdit.html页面
                        var Data = new { ID = strID, Name = strPersonName, Email = strEmail };
                        strHtml = Common_Nvelocity.Template_Nvelocity("PersonEdit.html", Data);
                    }

                }
            }

            context.Response.Write(strHtml);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

View Code

  C. 以上七个艾德it页面完毕了:大家点击编辑的时候,把通过UGL450L传值把 ID,Name,Email属性参数字传送递到 Person艾德it.ashx页面中

   一Person艾德it.ashx呈现传递过来的新闻二对Person艾德it.ashx中的新闻举行改造并付诸  三改换形成后跳转到PersonAdd.ashx页面展现PersonList列表

-----------------------------------------------GIF图片演示效果------------------------------------------------

web前端 27

web前端, 伍, 达成Delete功能: 壹PersonAdd.html中增进"删除"超链接 二新建PersonDelete.ashx管理删除动作  2点击 “删除”,通过U奥迪Q5L把相应的ID传值到PersonDelete.ashx实行删减

  PersonAdd.html 和 PersonDelete.ashx:

web前端 28web前端 29

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form action="PersonAdd.ashx" method="get">
        姓名:
        <input type="text" name="PersonName" />
        <br />
        邮箱:<input type="email" name="Email" />
        <input type="submit" value="新增" />
    </form>
    <ul>
        #foreach($d in $data)
        <li>姓名:$d.Name &nbsp; 邮箱:$d.email&nbsp; <a href="PersonEdit.ashx?ID=$d.ID&Name=$d.Name&Email=$d.email">编辑</a>&nbsp;&nbsp; <a href="PersonDelete.ashx?ID=$d.ID">删除</a></li>
        #end
    </ul>
</body>
</html>

View Code

web前端 30web前端 31

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

namespace CIUD_NVelocitySample
{
    /// <summary>
    /// PersonDelete 的摘要说明
    /// </summary>
    public class PersonDelete : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";

            //实现Person的删除功能能后,跳转到 PersonAdd.ashx
            string strID = context.Request.QueryString["ID"];

            string sqlDel = "delete from [NVelocity_Sample].[dbo].[T_Person] where [ID]='"   strID   "' ";
            SQLHelper sqlH = new SQLHelper();
            int numSucc = sqlH.ExecuteNonQuery(sqlDel, CommandType.Text);

            if (numSucc == 1)
            {
                //删除成功,返回页面
                context.Response.Redirect("PersonAdd.ashx");
            }
            else
            {
                //输出删除失败
                context.Response.Write("删除失败");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

View Code

-----------------------------------------------GIF图片演示效果------------------------------------------------web前端 32

上述达成了简便易行的CIUD功效。

6,添加City表,T_Perons中新添字段:CityID

web前端 33web前端 34

USE [NVelocity_Sample]
GO

/****** Object:  Table [dbo].[T_LiveCity]    Script Date: 2015/5/15 14:51:21 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[T_LiveCity](
    [ID] [decimal](18, 0) IDENTITY(1,1) NOT NULL,
    [CityName] [nvarchar](50) NOT NULL
) ON [PRIMARY]

GO

View Code

web前端 35     web前端 36

柒,CIUD页面中 增加对应的居住城市:

Insert页面:PersonAdd.ashx

web前端 37

Update页面:PersonEdit.ashx

web前端 38

 

 

加上下拉框以往的完全代码下载: Demo Download

 

  

 

本文由www.bifa365365.com发布于web前端,转载请注明出处:微信小程序支付之c,微信小程序服务端获取用户

关键词: www.bifa3653