最近由於項目需要做一個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來作為反序列化的載體,反序列化成功之后的操作就更加簡單了,根據你的業務邏輯把這些數據做出相應的操作即可。
呵呵,在這高手雲集的地方班門弄斧了,文章中錯誤之處還請給位看官指出和分享。讓我們共同進步!
