ASP.NET前后台交互之JSON数据

时间:2022-11-28 18:56:33

  最近由于项目需要做一个Ajax的搜集单表单的多重数据的需求,所以就采用了前端JQuery保存Object对象之后转换成JSON的数据源传递给后台处理的这样的形式,相信有不少人大多时候是接收后台给出的JSON数据格式,拿到前端来显示的形式。当然这也是我个人的经历简介而已,高手勿喷,写这篇文章的目的也是为了以后忘记了能够帮助会议。或许真的能够帮助到某些像我一个涉世不深的菜鸟。O(∩_∩)O

  以下是部分关键代码  

  首先是HTML代码:

    <fieldset>
        <legend>基本信息</legend>
        <div class="add_main" id="wrapper_add">
            <div id="errorInfo" class="error container"></div>
            <table width="100%" border="0" cellpadding="0" cellspacing="0" class="addForm">
                <tr>
                    <th>目标对象:</th>
                    <td>
                        <asp:TextBox ID="obj_tbx" ClientIDMode="Static" CssClass="input" runat="server" Width="280px"></asp:TextBox>
                    </td>
                    <th width="18%">工作组:</th>
                    <td width="32%">
                        <asp:DropDownList ID="Group_ddl" ClientIDMode="Static" runat="server" Width="120px"></asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <th width="18%">项目分类:</th>
                    <td width="32%">
                        <asp:DropDownList ID="ProjectType_ddl" ClientIDMode="Static" runat="server" Width="200px"></asp:DropDownList>
                    </td>
                    <th width="18%">等级积分:</th>
                    <td width="32%">
                        <asp:DropDownList ID="score_ddl" ClientIDMode="Static" runat="server" Width="120px"></asp:DropDownList>
                    </td>
                </tr>
                <tr>
                </tr>
                <tr>
                    <th>目标地址:</th>
                    <td colspan="3">
                        <uc1:City ID="City1" runat="server" />
                        <input id="adress_tbx" type="text" class="input" style="width: 280px;" />
                        <a href="javascript:void(0);" onclick="Address_Click()">添加地址</a>
                        <div id="result">
                        </div>
                </tr>
                <tr>
                    <th>要求完成时间:</th>
                    <td colspan="3">
                        <asp:TextBox ID="request_tbx" CssClass="ipt_date" ClientIDMode="Static" runat="server" onclick="WdatePicker()" Width="120px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <th valign="top">特别要求:</th>
                    <td colspan="3">
                        <asp:TextBox ID="special_tbx" ClientIDMode="Static" runat="server" Height="100px" TextMode="MultiLine" Width="501px"></asp:TextBox>
                    </td>
                </tr>
            </table>
        </div>
    </fieldset>
    <fieldset>
        <legend>附件资料</legend>
        <uc1:Uploadify ID="Uploadify1" runat="server" />
        <table id="tb_fileview" style="display: none;" width="100%" border="0" cellpadding="0" cellspacing="0" class="list">
            <thead>
                <tr>
                    <th>文件名称</th>
                    <th>文件大小</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </fieldset>
    <div class="add_button">
        <input type="button" class="btn_yes" name="btn_release" id="btn_release" onclick="SubmitTask_Click()" value="发布任务" />    
        <input type="button" class="btn_yes" name="btn_add" id="btn_update" style="display: none;" onclick="UpdateSubtasks_Click()" value="更新任务" />    
        <input type="button" class="btn_yes" name="btn_add" id="btn_add" onclick="AddSubtasks_Click()" value="添加子任务" />
    </div>

  Javascript代码:

<script type="text/javascript" charset="utf-8">
        var TaskAddressArray = new Array();//任务地址集合
        var TaskArray = new Array();//任务集合
        //Array Remove - By James (MIT Licensed)  
        Array.prototype.remove = function (from, to) {
            var rest = this.slice((to || from) + 1 || this.length);
            this.length = from < 0 ? this.length + from : from;
            return this.push.apply(this, rest);
        };
        ///获取任务对象信息
        function gettaskmodel(Addresslist) {
            var taskmodel = new Object();
            taskmodel.Goal = $("#obj_tbx").val();//目标对象
            taskmodel.Group = $("#Group_ddl").val();//工作组值
            taskmodel.GroupName = $("#Group_ddl").find("option:selected").text();//工作组名称
            taskmodel.ProjectType = $("#ProjectType_ddl").val();//项目分类值
            taskmodel.ProjectTypeName = $("#ProjectType_ddl").find("option:selected").text();//项目分类名称
            taskmodel.Score = $("#score_ddl").val();//等级积分值
            taskmodel.ScoreName = $("#score_ddl").find("option:selected").text();//等级积分名称
            taskmodel.CarryDate = $("#request_tbx").val();//要求完成时间
            taskmodel.Special = $("#special_tbx").val();//特殊要求
            taskmodel.Address = Addresslist;//任务地址集合
            taskmodel.UploadFile = eval($("#hdJSON").val());//获取上传文件

            return taskmodel;
        }
        ///获取地址对象信息
        function gettaskaddressmodel() {
            var taskaddress = new Object();//调查地址
            taskaddress.province = $("#ddl_province").val();//省份代码
            taskaddress.provinceName = $("#ddl_province").find("option:selected").text();//省份名称
            taskaddress.city = $("#ddl_city").val();//城市代码
            taskaddress.cityName = $("#ddl_city").find("option:selected").text();//城市名称
            taskaddress.counties = $("#ddl_counties").val();//区域代码
            taskaddress.countiesName = $("#ddl_counties").find("option:selected").text();//区域名称
            taskaddress.detail = $("#adress_tbx").val();//详细地址

            return taskaddress;
        }
        //清空表单
        function ClearForm() {
            $("#obj_tbx").val("");
            $(".addForm select").find("option[value='']").attr("selected", true);
            $("#request_tbx").val("");
            $("#special_tbx").val("");
            $("#adress_tbx").val("");
            $("#hdJSON").val("");
            $("#tb_fileview").attr("style", "display:none");
            $("#tb_fileview").find("tbody").html("");
            TaskAddressArray = [];//清空地址数组
            ShowAddress();

        }
        //表单赋值
        function SetForm(index) {
            $("#obj_tbx").val(TaskArray[index].Goal);
            $("#Group_ddl").find("option[value='" + TaskArray[index].Group + "']").attr("selected", true);
            $("#ProjectType_ddl").find("option[value='" + TaskArray[index].ProjectType + "']").attr("selected", true);
            $("#score_ddl").find("option[value='" + TaskArray[index].Score + "']").attr("selected", true);
            $("#request_tbx").val(TaskArray[index].CarryDate);
            $("#special_tbx").val(TaskArray[index].Special);
            $("#hdJSON").val(JSON.stringify(TaskArray[index].UploadFile));
            TaskAddressArray = TaskArray[index].Address;
            ShowAddress();
            ShowUpLoadFile(index);
            $("#btn_release,#btn_add").attr("style", "display:none");
            $("#btn_update").removeAttr("style").attr("onclick", "UpdateForm(" + index + ")");
        }
        //更新列表
        function UpdateForm(index) {
            var TaskModel = gettaskmodel(TaskAddressArray);
            ClearForm();
            TaskArray.splice(index, 1, TaskModel);
            ShowTaskView();
            $("#btn_release,#btn_add").removeAttr("style");
            $("#btn_update").removeAttr("onclick").attr("style", "display:none");
        }
        //添加地址事件
        function Address_Click() {
            var TaskAddressModel = gettaskaddressmodel();
            if (TaskAddressModel.province == "" || TaskAddressModel.city == "" || TaskAddressModel.counties == "" || TaskAddressModel.detail == "") {
                alert("您填写的地址不完整,请填写完整!");
                return;
            }
            TaskAddressArray.push(TaskAddressModel);
            ShowAddress();
        }
        ///显示地址
        function ShowAddress() {
            $("#result").html("");
            for (var i = 0; i < TaskAddressArray.length; i++) {
                $("#result").append("<p>" +
                    TaskAddressArray[i].provinceName +
                    TaskAddressArray[i].cityName +
                    TaskAddressArray[i].countiesName +
                    TaskAddressArray[i].detail + "     <a href=\"javascript:void(0);\" onclick=\"RemoverAddress_Click(" + i + ")\">删除</a></p>");
            }
        }
        function ShowUpLoadFile(index) {
            var FileArray = eval($("#hdJSON").val());
            if (FileArray.length > 0) {
                $("#tb_fileview").removeAttr("style");
                $("#tb_fileview").find("tbody").html("");
                for (var i = 0; i < FileArray.length; i++) {
                    var trStr = "<tr>" +
                        "<td>" + FileArray[i].FileName + "</td>" +
                        "<td>" + FileArray[i].FileSize + "</td>" +
                        "<td>" +
                        "<a href=\"javascript:void(0)\" onclick=\"RemoveFileView_Click(" + i + ")\">删除</a></td>" +
                    "</tr>";
                    $("#tb_fileview").find("tbody").append(trStr);
                }
            }
        }
        //移除上传文件
        function RemoveFileView_Click(index) {
            var FileArray = eval($("#hdJSON").val());
            FileArray.remove(index);
            $("#hdJSON").val(JSON.stringify(FileArray));
            ShowUpLoadFile();
        }
        //移除地址数组
        function RemoverAddress_Click(id) {
            TaskAddressArray.remove(id);
            ShowAddress();
        }
        //移除任务数组
        function RemoveTaskView_Click(id) {
            TaskArray.remove(id);
            ShowTaskView();
        }
        ///添加子任务
        function AddSubtasks_Click() {
            if (TaskAddressArray.length == 0) {
                alert("您尚未添加任务地址,请正确添加任务地址!");
                return;
            }
            var TaskModel = gettaskmodel(TaskAddressArray);
            ClearForm();
            TaskArray.push(TaskModel);
            ShowTaskView();
        }
        //任务列表
        function ShowTaskView() {
            $("#tb_taskview").find("tbody").html("");
            if (TaskArray.length == 0) {
                alert("没有找到有效的任务数据!");
                return;
            }
            var ico = "";
            for (var i = 0; i < TaskArray.length; i++) {
                if (i == 0) {
                    ico = "<span style=\"color:red;font-weight: bold;\">(主)</span>";
                } else {
                    ico = "<span style=\"color:green;font-weight: bold;\">(次)</span>";
                }
                var trStr = "<tr>" +
                    "<td>" + ico + "</td>" +
                    "<td>" + TaskArray[i].GroupName + "</td>" +
                    "<td>" + TaskArray[i].ProjectTypeName + "</td>" +
                    "<td>" + TaskArray[i].ScoreName + "</td>" +
                    "<td>" + TaskArray[i].Goal + "</td>" +
                    "<td>" + TaskArray[i].Address[0].provinceName + "</td>" +
                    "<td>" + TaskArray[i].Address[0].cityName + "</td>" +
                    "<td>" + TaskArray[i].Address[0].countiesName + "</td>" +
                    "<td>" + TaskArray[i].Address[0].detail + "</td>" +
                    "<td>" + TaskArray[i].CarryDate + "</td>" +
                    "<td>" + TaskArray[i].Special + "</td>" +
                    "<td>" +
                    "<a href=\"javascript:void(0)\" onclick=\"SetForm(" + i + ")\">编辑</a>  " +
                    "<a href=\"javascript:void(0)\" onclick=\"RemoveTaskView_Click(" + i + ")\">删除</a></td>" +
                "</tr>";
                $("#tb_taskview").find("tbody").append(trStr);
            }
        }
        //提交任务信息
        function SubmitTask_Click() {
            if (TaskArray.length == 0) {
                alert("没有可以提交的任务信息,请确认已添加完成!");
                return;
            }
            if (confirm("您确定要提交该任务吗?")) {
                $.ajax({
                    type: "POST",
                    dataType: "JSON",
                    url: "/AjaxHandler/TaskHandler.ashx?action=save",
                    data: { TaskModel: JSON.stringify(TaskArray) },
                    success: function (data) {
                        if (data.code == 0) {
                            if (confirm(data.msg)) {
                                location.href = "TaskTracking.aspx";
                            } else {
                                location.href = location.href;
                            }
                        } else {
                            alert(data.msg);
                        }
                    },
                    error: function () {
                        alert("任务信息提交失败,请稍候重试或联系管理员解决!");
                    }
                });
            }
        }
    </script>

  处理接口代码:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IMPlatform.Web.App_Code;
using IMPlatform.DomainEntities;
using IMPlatform.Service.Business;
using IMPlatform.Service;
using System.Web.SessionState;

namespace IMPlatform.Web.AjaxHandler
{
    /// <summary>
    /// TaskHandler 的摘要说明
    /// </summary>
    public class TaskHandler : IHttpHandler, IRequiresSessionState
    {
        IMPlatform.Web.App_Code.BackJson<Task[]> _json = new App_Code.BackJson<Task[]>();
        TaskService tService = new TaskService();
        TaskTypeService ptService = new TaskTypeService();
        TaskLogService tlogService = new TaskLogService();
        public void ProcessRequest(HttpContext context)
        {
            string action = context.Request["action"] == null ? "" : context.Request["action"].ToString();
            switch (action)
            {
                case "save":
                    SaveTask(context);
                    break;
                default:
                    _json.code = -10;
                    _json.msg = "参数错误!";
                    context.Response.Write(JsonConvert.SerializeObject(_json));
                    break;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// 保存任务信息
        /// </summary>
        /// <param name="context"></param>
        private void SaveTask(HttpContext context)
        {
            try
            {
                string taskStr = context.Request["TaskModel"] == null ? "" : context.Request["TaskModel"].ToString();
                PermissionLogic logic = new PermissionLogic(System.Web.HttpContext.Current);
                string userid = logic.CurrentUserInfomation.UserID;
                List<Task> TaskModelList = JsonHelper<Task>.JsonToList(taskStr);
                string MainNum = "";//主任务编号
                foreach (Task item in TaskModelList)
                {
                    task TaskEntity = new task();
                    TaskEntity.Address = item.Address[0].detail;
                    TaskEntity.AreaId = item.Address[0].counties;
                    TaskEntity.CityId = item.Address[0].city;
                    TaskEntity.ProvinceId = item.Address[0].province;
                    TaskEntity.CreateDate = DateTime.Now;
                    TaskEntity.Creator = userid;
                    TaskEntity.Grade = Convert.ToInt32(item.Score);

                    System.Collections.Generic.List<task> list = tService.GetTaskList();
                    bool flag = true;
                    string num = "";
                    while (flag)
                    {
                        num = String.Format("{0:D6}", new Random().Next(999999));

                        if (list.Where(x => x.TaskNo == num).Count() == 0)
                        {
                            flag = false;
                        }
                    }
                    TaskEntity.TaskNo = num;
                    TaskEntity.ParentTaskNo = MainNum;
                    if (MainNum == "")
                    {
                        MainNum = num;
                    }
                    TaskEntity.ProjectTypeID = item.ProjectType;
                    TaskEntity.RequireFinishDate = Convert.ToDateTime(item.CarryDate);
                    TaskEntity.SpecialRequest = item.Special;
                    TaskEntity.TargetObject = item.Goal;
                    TaskEntity.TaskId = Guid.NewGuid().ToString();
                    TaskEntity.TaskStatus = 0;
                    TaskEntity.Group = item.Group;
                    #region 组织地址信息
                    List<taskaddress> addresslist = new List<taskaddress>();
                    foreach (TaskAddress Address in item.Address)
                    {
                        taskaddress tk_address = new taskaddress();
                        tk_address.ProvinceId = Address.province;
                        tk_address.CityId = Address.city;
                        tk_address.AreaId = Address.counties;
                        tk_address.Address = Address.detail;
                        addresslist.Add(tk_address);
                    }
                    #endregion
                    #region 组织上传文件信息
                    if (item.UploadFile != null)
                    {
                        List<taskfile> tflist = new List<taskfile>();
                        foreach (var File in item.UploadFile)
                        {
                            taskfile tf = new taskfile();
                            tf.FileName = File.FileName;
                            tf.FilePath = File.FilePath;
                            tf.SaveFileName = File.SaveName;
                            tf.TaskId = TaskEntity.TaskId;
                            u_user user = new PermissionLogic(HttpContext.Current).CurrentUser;
                            tf.UploadUser = user != null ? user.UserID : Guid.Empty.ToString();
                            tf.UploadDate = DateTime.Now;
                            tf.FileStatus = 1;
                            tflist.Add(tf);
                        }
                        tService.AddTaskFile(tflist);
                    }
                    #endregion
                    tService.AddTask(TaskEntity, addresslist);
                }
                _json.code = 0;
                _json.msg = "任务发布成功!是否前去任务管理查看?";
                context.Response.Write(JsonConvert.SerializeObject(_json));
            }
            catch (Exception ex)
            {
                _json.code = -1;
                _json.msg = "系统异常,请稍候重试!异常消息:" + ex.Message;
                context.Response.Write(JsonConvert.SerializeObject(_json));
            }
        }
    }
}

  在这里需要注意的是在处理函数中反序列化的时候,一定要创建一个跟你前端组织的JSON数据一样的Model来作为反序列化的载体,反序列化成功之后的操作就更加简单了,根据你的业务逻辑把这些数据做出相应的操作即可。

  呵呵,在这高手云集的地方班门弄斧了,文章中错误之处还请给位看官指出和分享。让我们共同进步!