zoukankan      html  css  js  c++  java
  • C#:数据交互

    JS与Web交互:http://www.docin.com/p-76710976.html

    一、WinForm的WebBrowser控件与JS交互数据:

      1、C#类内的代码执行JS脚本函数:

      给C#类中的WebBrowser控件加载一个包含JS脚本的HTML页面:this.webBrowser1.Url = new System.Uri(Application.StartupPath + "\kindeditor\e.html", System.UriKind.Absolute);

      C#类内的代码执行JS脚本的setContent(str)函数:webBrowser.Document.InvokeScript("setContent", new object[] { content });//content为C#中自定义的string类型字段。

      2、脚本执行C#类内的函数:

      WebBrowser.ObjectForScripting:返回或者设置一个对象,可以通过脚本访问包含的代码。譬如:在C#类中设置this.webBrowser.ObjectForScripting = this; 则webBrowser包含的脚本就可以执行this(C#类)类内的函数(如:GetContent())。JS脚本执行this类内的GetContent公共方法:window.external.GetContent();

    二、Web与JS交换数据

      1、JS($.ajax)向制定的.ashx文件中的方法传输数据。需设置url项为制定文件的方法,如: url: "Service/EasyUiService.ashx?Method=Login"。具体代码如下:

        <script type="text/javascript">
            $(function() {
                $("#loginWindow").window({
                    title: '登陆窗口',
                     290,
                    height: 180,
                    modal: true,
                    shadow: false,
                    closable: false,
                    maximizable: false,
                    minimizable: false,
                    collapsible: false,
                    resizable: false
                });
    
                $("#btnLogin").click(function() {
                    var username = document.getElementById("username").value;
                    var password = document.getElementById("password").value;
    
                    loginSys(username, password);
                });
    
                $("#aboutSys").click(function() {
                    $.messager.alert('关于', 'JQuery EasyUi练习!', 'info');
                });
            });
    
            //登陆操作
            function loginSys(username,password) {
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    //cache:true,
                    url: "Service/EasyUiService.ashx?Method=Login",
                    data: { username: username, password: password },
                    success: function(json) {
                        if (json.Flag[0].Status == 1) {
                            window.location.href = "Index.aspx";
                        }
                        else {
                            $.messager.alert('错误', '账号或密码错误!', 'error');
                        }
                    },
                    error: function() {
                        $.messager.alert('错误', '获取账号信息失败...请联系管理员!', 'error');
                    }
                });
            }
        </script>
    View Code

      EasyUiService.ashx文件中的Login函数对应代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.SessionState;
    using System.Reflection;
    using System.Text;
    
    namespace EasyUi.Web.Service
    {
        public class EasyUiService : IHttpHandler, IRequiresSessionState
        {
            HttpRequest Request;
            HttpResponse Response;
            HttpSessionState Session;
            HttpServerUtility Server;
            HttpCookie Cookie;
    
            public void ProcessRequest(HttpContext context)
            {
                //不让浏览器缓存
                context.Response.Buffer = true;
                context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
                context.Response.AddHeader("pragma", "no-cache");
                context.Response.AddHeader("cache-control", "");
                context.Response.CacheControl = "no-cache";
                context.Response.ContentType = "text/plain";
    
                Request = context.Request;
                Response = context.Response;
                Session = context.Session;
                Server = context.Server;
    
                string method = Request["Method"].ToString();
                MethodInfo methodInfo = this.GetType().GetMethod(method);
                methodInfo.Invoke(this, null);
            }
    
            /// <summary>
            /// 登陆
            /// </summary>
            public void Login()
            {
                string username = Request["username"].ToString();
                string password = Request["password"].ToString();
    
                int flag = UserAccess.GetInstance().Login(username, password);
                int? roleId = RoleAccess.GetInstance().GetRoleIdByUsername(username);
    
                Cookie = new HttpCookie("RoleInfo");
                Cookie["roleId"] = roleId.ToString();
                Cookie.Expires = DateTime.Now.AddMonths(1);
                Response.Cookies.Add(Cookie);
    
                JsonConvert<object> jc = new JsonConvert<object>();
                Response.Write(jc.ToStatus(flag));
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
    View Code

      Response.Write()返回值

      注释:ashx是一般应用程序,我现在就是用jquery和.NET开发网站的,我们用ashx作为通讯层,jquery用post传参,ashx页面接收参数,然后返回值。浏览页面时是无法看到我们编写的代码的。

       2、Web与JQuery-EasyUI交换数据

        1)树:通过URL地址指向指定文件中的函数获取Json数据

      $(function() {
                //系统管理树
                $("#sysManageTree").tree({
                    checkbox: false,
                    url: 'Service/EasyUiService.ashx?Method=GetSysManageTree&RoleId=' + GetCookie("RoleInfo").substring(7,8),
                    onClick: function(node) {
                        $(this).tree('toggle', node.target);
    
                        //$("#contentPage").attr("src", node.attributes);
                        loadFrame(node.attributes);
                    }
    //                onContextMenu: function(e, node) {
    //                    e.preventDefault();
    //                    $('#sysManageTree').tree('select', node.target);
    //                    $('#treeMenu').menu('show', {
    //                        left: e.pageX,
    //                        top: e.pageY
    //                    });
    //                }
                });
    }
    View Code

        2)数据网格:通过URL地址指向指定文件中的函数获取Json数据

    $('#roleManageGrid').datagrid({
                    //title: '角色管理',
                    //iconCls: 'icon-save',
                    collapsible: false,
                    fitColumns: true,
                    singleSelect: true,
                    remoteSort: false,
                    sortName: 'RoleName',
                    sortOrder: 'desc',
                    nowrap: true,
                    method: 'get',
                    loadMsg: '正在加载数据...',
                    url: '../Service/EasyUiService.ashx?Method=GetRoleInfo',
                    frozenColumns: [[
                        { field: 'ck', checkbox: true }
                    ]],
                    columns: [[
                        { field: 'RoleId', title: '角色ID',  80, sortable: true },
                        { field: 'RoleName', title: '角色名称',  100,sortable:true },
                        { field: 'RoleDes', title: '角色描述',  100 }
                    ]],
                    pagination: true,
                    pageNumber: 1,
                    rownumbers: true,
                    toolbar:
                    [
                        {
                            id: 'btnAdd',
                            text: '添加角色',
                            iconCls: 'icon-add',
                            handler: function() {
                                $("#roleName").val("");
                                $("#roleDes").val("");
                                addRoleDialog();
                            }
                        },
                        '-',
                        {
                            id: 'btnEdit',
                            text: '编辑角色',
                            iconCls: 'icon-edit',
                            handler: function() {
                                var selected = $('#roleManageGrid').datagrid('getSelected');
                                if (selected) {
                                    var roleId = selected.RoleId;
                                    var roleName = selected.RoleName;
                                    var roleDes = selected.RoleDes;
                                    $("#roleName").val(roleName);
                                    $("#roleDes").val(roleDes);
                                    editRoleDialog();
                                }
                            }
                        },
                        '-',
                        {
                            id: 'btnDelete',
                            text: '删除角色',
                            disabled: true,
                            iconCls: 'icon-remove',
                            handler: function() {
                            }
                        }
                    ],
                    onLoadSuccess: function() {
                        //$("#roleManageGrid").datagrid('reload');
                    },
                    onClickRow: function(rowIndex, rowData) {
                        var roleId = rowData.RoleId;
                        loadTree(roleId);
                        RoleId = roleId;
                    }
                });
            });
    View Code

      参考:

      对应的具体函数(可跳过):

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.SessionState;
    using System.Reflection;
    using System.Text;
    
    using XQH.EasyUi.Access;
    using XQH.EasyUi.Entity;
    
    namespace XQH.EasyUi.Web.Service
    {
        public class EasyUiService : IHttpHandler, IRequiresSessionState
        {
            HttpRequest Request;
            HttpResponse Response;
            HttpSessionState Session;
            HttpServerUtility Server;
            HttpCookie Cookie;
    
            public void ProcessRequest(HttpContext context)
            {
                //不让浏览器缓存
                context.Response.Buffer = true;
                context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
                context.Response.AddHeader("pragma", "no-cache");
                context.Response.AddHeader("cache-control", "");
                context.Response.CacheControl = "no-cache";
                context.Response.ContentType = "text/plain";
    
                Request = context.Request;
                Response = context.Response;
                Session = context.Session;
                Server = context.Server;
    
                string method = Request["Method"].ToString();
                MethodInfo methodInfo = this.GetType().GetMethod(method);
                methodInfo.Invoke(this, null);
            }
    
            /// <summary>
            /// 登陆
            /// </summary>
            public void Login()
            {
                string username = Request["username"].ToString();
                string password = Request["password"].ToString();
    
                int flag = UserAccess.GetInstance().Login(username, password);
                int? roleId = RoleAccess.GetInstance().GetRoleIdByUsername(username);
    
                Cookie = new HttpCookie("RoleInfo");
                Cookie["roleId"] = roleId.ToString();
                Cookie.Expires = DateTime.Now.AddMonths(1);
                Response.Cookies.Add(Cookie);
    
                JsonConvert<object> jc = new JsonConvert<object>();
                Response.Write(jc.ToStatus(flag));
            }
    
            
            /// <summary>
            /// 获取系统管理树
            /// </summary>
            public void GetSysManageTree()
            {
                //SetModuleType("01");
                SetModulePermission("01");
            }
    
            /// <summary>
            /// 工作管理树
            /// </summary>
            public void GetWorkManageTree()
            {
                SetModulePermission("02");
            }
    
            /// <summary>
            /// 日常管理
            /// </summary>
            public void GetDailyManageTree()
            {
                SetModulePermission("03");
            }
    
            /// <summary>
            /// 其他事项
            /// </summary>
            public void GetOtherTree()
            {
                SetModulePermission("04");
            }
    
            /// <summary>
            /// 设置模块类型(现在只支持数据库修改)
            /// </summary>
            /// <param name="pid"></param>
            private void SetModuleType(string pid)
            {
                List<FunctionItemEntity> lsC = FunctionItemAccess.GetInstance().GetFunctionItemByPid(pid);
                List<FunctionItemEntity> lsP = FunctionItemAccess.GetInstance().GetFunctionNameById(pid);
                JsonConvert<FunctionItemEntity> jc = new JsonConvert<FunctionItemEntity>();
                Response.Write(jc.ToTreeNode(lsC, lsP));
            }
    
            /// <summary>
            /// 设置权限树
            /// </summary>
            public void SetPermissionTree()
            {
                int roleId = Convert.ToInt32(Server.UrlDecode(Request["RoleId"].ToString()));
                string resultStr = string.Empty;
    
                List<string> lsP = new List<string>();
                lsP = PermissionAccess.GetInstance().GetParentPermission();
                //此处省略得到数据列表的代码
                resultStr = "";
                resultStr += "[";
                foreach (string item in lsP)
                {
                    resultStr += "{";
    
                    List<PermissionEntity> lsC = new List<PermissionEntity>();
                    lsC = PermissionAccess.GetInstance().GetChildPermission(item);
                    //如果某变电站下有线路
                    if (lsC.Count > 0)
                    {
                        resultStr += string.Format(""id": "{0}", "text": "{1}", "state": "closed"", item, item);
                        resultStr += ","children":[";
    
                        for (int i = 0; i < lsC.Count; i++)
                        {
                            resultStr += "{";
                            resultStr += string.Format(""id": "{0}", "text": "{1}","checked":{2} ", lsC[i].PermissionId, lsC[i].OperationName, RolePermissionAccess.GetInstance().IsPermissionOn(roleId,lsC[i].PermissionId) == null ? "false" : "true");
                            resultStr += "},";
                        }
                        resultStr = resultStr.Substring(0, resultStr.Length - 1);
                        resultStr += "]";
                    }
                    else
                    {
                        resultStr += string.Format(""id": "{0}", "text": "{1}" ", item, item);
                    }
                    resultStr += "},";
                }
    
                resultStr = resultStr.Substring(0, resultStr.Length - 1);
                resultStr += "]";
    
                Response.Write(resultStr);      
            }
    
            /// <summary>
            /// 设置模块操作权限
            /// </summary>
            /// <param name="pid">父ID</param>
            private void SetModulePermission(string pid)
            {
                int roleId = Convert.ToInt32(Request.QueryString["RoleId"].ToString());
    
                List<FunctionItemEntity> lsC = FunctionItemAccess.GetInstance().GetOperationPermission(pid, roleId);
                List<FunctionItemEntity> lsP = FunctionItemAccess.GetInstance().GetFunctionNameById(pid);
                JsonConvert<FunctionItemEntity> jc = new JsonConvert<FunctionItemEntity>();
                Response.Write(jc.ToTreeNode(lsC, lsP));
            }
    
            /// <summary>
            /// 获取角色信息
            /// </summary>
            public void GetRoleInfo()
            {
                List<RoleEntity> ls = RoleAccess.GetInstance().GetRoleInfo();
                JsonConvert<RoleEntity> jc = new JsonConvert<RoleEntity>();
                Response.Write(jc.ToDataGrid(ls, ls.Count));
            }
    
            /// <summary>
            /// 获取账号信息
            /// </summary>
            public void GetUserInfo()
            {
                List<UserEntity> ls = UserAccess.GetInstance().GetUserInfo();
                JsonConvert<UserEntity> jc = new JsonConvert<UserEntity>();
                Response.Write(jc.ToDataGrid(ls,ls.Count));
            }
    
            /// <summary>
            /// 设置权限
            /// </summary>
            public void SetPermission()
            {
                string isChecked = Request["IsChecked"].ToString();
                int roleId = Convert.ToInt32(Request["RoleId"].ToString());
                string permissionId = Request["PermissionId"].ToString();
    
                //如果为true,则添加权限
                if (isChecked == "true")
                {
                    RolePermissionAccess.GetInstance().AddPermission(roleId, permissionId);
                }
                else
                {
                    RolePermissionAccess.GetInstance().DeletePermission(roleId, permissionId);
                }
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
    View Code

      把对象转换成JSON对象(可跳过)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Text;
    
    using Newtonsoft.Json;
    using XQH.EasyUi.Entity;
    
    /// <summary>
    /// 把对象转换成JSON对象
    /// </summary>
    public class JsonConvert<T>
    {   
    
        //------jquery ui tree json data------
        //------树节点只支持 id,text,children,attributes,checked,state,iconCls等属性
        //[
        //    {
        //        "id":"01",
        //        "text":"系统管理",
        //        "parentid":"0",
        //        "attributes":"",
        //        "children":
        //        [
        //            {
        //                "id":"0101",
        //                "text":"模块管理",
        //                "parentid":"01",
        //                "attributes":"web/modulemanage.aspx"
        //            }
        //        ]
        //    }
        //]
    
        //------jquery ui datagrid json data------
        //{                                                      
        //    "total":5,                                                      
        //    "rows":[                                                          
        //        {"RoleId":"001","RoleName":"Name 1","RoleDes":"Address 11"},
        //        {"RoleId":"002","RoleName":"Name 1","RoleDes":"Address 11"},
        //        {"RoleId":"003","RoleName":"Name 1","RoleDes":"Address 11"},
        //        {"RoleId":"004","RoleName":"Name 1","RoleDes":"Address 11"},
        //        {"RoleId":"005","RoleName":"Name 1","RoleDes":"Address 11"}     
        //    ]                                                          
        //}
     
        //------jquery ui flag json data------
        //{
        //    "Flag":[{"Status":"1"}]
        //}
    
        /// <summary>
        ///系统树节点数据
        /// </summary>
        /// <param name="lsC">子信息</param>
        /// <param name="lsP">父信息</param>
        /// <returns></returns>
        public StringBuilder ToTreeNode(List<T> lsC,List<T> lsP)
        {
            StringBuilder jsonData = new StringBuilder();
    
            jsonData.Append("[");
            jsonData.Append(JavaScriptConvert.SerializeObject(lsP[0]).ToLower());
            jsonData.Replace("}", ",");
            jsonData.Append(""children":[");
    
            foreach (T item in lsC)
            {
                string jsonGroup = JavaScriptConvert.SerializeObject(item);
                jsonData.Append(jsonGroup.ToLower());
                jsonData.Append(",");
            }
    
            //去掉末尾“,”号
            if (lsC.Count > 0)
                jsonData = jsonData.Remove(jsonData.Length - 1, 1);
    
            jsonData.Append("]}]");
            jsonData.Replace("functionname", "text");
            jsonData.Replace("url", "attributes");
    
            return jsonData;
        }
    
        public StringBuilder ToCheckedTreeNode(List<T> lsC, List<string> lsP)
        {
            StringBuilder jsonData = new StringBuilder();
    
            jsonData.Append("[{");
    
            foreach (string str in lsP)
            {
                jsonData.Append(""id":");
                jsonData.Append("0");
                jsonData.Append(",");
                jsonData.Append(""text":");
                jsonData.Append(str);
                jsonData.Append(",");
                jsonData.Append(""children":[");
            }
    
            return jsonData;
        }
    
        /// <summary>
        /// 转换成datagrid格式的数据
        /// </summary>
        /// <param name="ls">数据集合</param>
        /// <param name="total">总数</param>
        /// <returns></returns>
        public StringBuilder ToDataGrid(List<T> ls,int total)
        {
            StringBuilder jsonData = new StringBuilder();
    
            jsonData.Append("{");
            jsonData.Append(""total":");
            jsonData.Append(total);
            jsonData.Append(",");
            jsonData.Append(""rows":");
            jsonData.Append("[");
    
            foreach (T item in ls)
            {
                string jsonGroup = JavaScriptConvert.SerializeObject(item);
                jsonData.Append(jsonGroup);
                jsonData.Append(",");
            }
    
            if (ls.Count > 0)
                jsonData = jsonData.Remove(jsonData.Length - 1, 1);
    
            jsonData.Append("]}");
    
            return jsonData;
        }
    
        /// <summary>
        /// 转换成状态格式的JSON数据
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public StringBuilder ToStatus(int status)
        {
            StringBuilder jsonData = new StringBuilder();
    
            jsonData.Append("{");
            jsonData.Append(""Flag":");
            jsonData.Append("[{");
            jsonData.Append(""Status":");
            jsonData.Append(status);
            jsonData.Append("}]");
            jsonData.Append("}");
            return jsonData;
        }
    
    }
    View Code

       3、其他Web与js交互问题(摘):

    问:
    1.如何在JavaScript访问C#函数?
    2.如何在JavaScript访问C#变量?
    3.如何在C#中访问JavaScript的已有变量?
    4.如何在C#中访问JavaScript函数?
    
    问题1答案如下:
    javaScript函数中执行C#代码中的函数:
    方法一:1、首先建立一个按钮,在后台将调用或处理的内容写入button_click中;
    2、在前台写一个js函数,内容为document.getElementById("btn1").click();
    3、在前台或后台调用js函数,激发click事件,等于访问后台c#函数;
    
    方法二:1、函数声明为public
    后台代码(把public改成protected也可以)
    public string ss()
    {
    return("a");
    }
    2、在html里用 <%=fucntion()% >可以调用
    前台脚本
    <script language=javascript >
    var a = " <%=ss()% >";
    alert(a);
    </script >
    方法三:1、 <script language="javascript" >
    <!--
    function __doPostBack(eventTarget, eventArgument)
    {
    var theForm = document.Form1; //指runat=server的form
    theForm.__EVENTTARGET.value = eventTarget;
    theFrom.__EVENTARGUMENT.value = eventArgument;
    theForm.submit();
    }
    -- >
    </script >
    <input id="Button1" type="button" name="Button1" value="按钮" onclick="javascript:__doPostBack( 'Button1 ', ' ')" >
    
    方法四: <script language="javascript" >
    function SubmitKeyClick()
    {
    if (event.keyCode == 13)
    {
    event.cancelBubble = true;
    event.returnValue = false;
    document.all.FunName.value="你要调用的函数名";
    document.form[0].submit();
    }
    }
    </script >
    
    <INPUT onkeypress="SubmitKeyClick()" id="aaa" type="text" >
    <input type="hidden" name="FunName" > 〈!--用来存储你要调用的函数 --〉
    
    在.CS里有:
    public Page_OnLoad()
    {
    if (!Page.IsPost())
    {
    string strFunName=Request.Form["FunName"]!=null?Request.Form["FunName"]:"";
    //根据传回来的值决定调用哪个函数
    switch(strFunName)
    {
    case "enter()":
    enter() ; //调用该函数
    break;
    case "其他":
    //调用其他函数
    break;
    default:
    //调用默认函数
    break;
    }
    }
    }
    
    public void enter()
    {
    //……比如计算某值
    }
    
    问题2.如何在JavaScript访问C#变量?
    答案如下:
    方法一:1、通过页面上隐藏域访问 <input id="xx" type="hidden" runat="server" >
    方法二:1、如后台定义了PUBLIC STRING N;前台js中引用该变量的格式为 ' <%=n% > '"+ <%=n% >+"
    方法三:1、或者你可以在服务器端变量赋值后在页面注册一段脚本
    " <script language= 'javascript ' >var temp=" + tmp + " </script >"
    tmp是后台变量,然后js中可以直接访问temp获得值。
    
    
    3.如何在C#中访问JavaScript的已有变量?
    
    答案如下:
    
    方法一:1、前台使用静态文本控件隐藏域,将js变量值写入其中;
    2、后台用request["id"]来获取值;
    
    方法二:可以用cookie或session
    
    
    4.如何在C#中访问JavaScript函数?
    答案如下:
    c#代码中执行javaScript函数:
    方法一:1、Page.RegisterStartupScript("ggg"," <script >SetVisible(1); </script >");
    方法二:使用Literal类,然后
    private void Button2_Click(object sender, System.EventArgs e)
    {
    string str;
    str=" <script language= 'javascript ' >";
    str+="selectRange()";
    str+=" </script >";
    //Literal1.Visible=true;
    Literal1.Text=str;
    }
    View Code

    4、Form之间交互

      1)通过属性(字段)、函数、事件等

    //Form1内的代码如下:
    
    //声明并实例化F2
            Form2 form2 = new Form2();
            private void Form1_Load(object sender, EventArgs e)
            {
                //添加本窗体的Size属性更变事件
                this.SizeChanged += new EventHandler(Form1_SizeChanged);
                //F2顶端显示
                form2.TopMost = true;
                //添加F2的滑动条的移动事件
                form2.trackBar1.Scroll += new EventHandler(trackBar1_Scroll);
                form2.Show();
                //固定F2的坐标
                form2.Location = this.Location;
            }
            /// <summary>
            /// Size属性更变事件
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void Form1_SizeChanged(object sender, EventArgs e)
            {
                form2.Size = this.Size;
            }
            /// <summary>
            /// 滑动条的移动事件
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void trackBar1_Scroll(object sender, EventArgs e)
            {
                //设置透明度
                this.Opacity = (double)form2.trackBar1.Value / 100.0;
            }
    View Code

     2)

  • 相关阅读:
    varnish4.X安装
    关于varnish缓存
    s3cmd的使用
    MarkdownPad 2
    Lua控制语句
    Lua表达式
    后端怎么防止重复提交?(常用的做法)
    Redis用setnx+expire实现分布式锁存在什么隐患,如何改进?
    推送消息为什么使用RocketMQ,而不使用Kafka?
    自定义线程池,如何最佳创建线程池
  • 原文地址:https://www.cnblogs.com/shenchao/p/4707392.html
Copyright © 2011-2022 走看看