【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

ASP.NET MVC系列文章

【01】浅谈Google Chrome浏览器(理论篇)

【02】浅谈Google Chrome浏览器(操作篇)(上)

【03】浅谈Google Chrome浏览器(操作篇)(下)

【04】浅谈ASP.NET框架

【05】浅谈ASP.NET MVC运行过程

【06】浅谈ASP.NET MVC 控制器

【07】浅谈ASP.NET MVC 路由

【08】浅谈ASP.NET MVC 视图

【09】浅谈ASP.NET MVC 视图与控制器传递数据

【10】浅谈jqGrid 在ASP.NET MVC中增删改查

【11】浅谈ASP.NET 页面之间传值的几种方式

【12】浅谈缓存技术在ASP.NET中的运用

【13】浅谈NuGet在VS中的运用

【14】浅谈ASP.NET 程序发布过程

【15】浅谈数据注解和验证

【16】浅谈依赖注入

【17】浅谈表单和HTML辅助方法

【18】浅谈基于APS.NET身份验证

【19】浅谈ASP.NET MVC 模型

【20】浅谈ASP.NET MVC 单元测试

【21】浅谈ASP.NET MVC网络安全;

【22】浅谈ASP.NET MVC八大类扩展

【23】再谈ASP.NET MVC Routing

【24】浅谈ASP.NET 高级话题

【25】浅谈大型ASP.NET MVC项目(含DEMO)

【26】下一系列:ASP.NET WebAPI

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查


1   概述

本篇文章主要是关于JqGrid的,主要功能包括使用JqGrid增删查改,导入导出,废话不多说,直接进入正题。

2   Demo相关

2.1   Demo展示

第一部分

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

第二部分

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

2.2  源码和DB下载

本来国庆上传到github上的,现在github有点问题,因此后期再传到github,有需要源码的,可以在评论区留下自己联系联系方式,我直接传给你。

3  公共模块

3.1 Model实体—EmployeeInfo

 using MVCCrud.Areas.DBUtility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web; namespace MVCCrud.Areas.JqGridDemo.Models
{
//EmployeeInfo实体类
public class EmployeeInfo
{
public string EmployeeID { get; set; }
public string EmployeeName { get; set; }
public string EmployeeMajor { get; set; }
public string EmployeeDepartment { get; set; }
public string EmployeeTel { get; set; }
public string EmployeeEmail { get; set; }
public string EmployeeJiGuan { get; set; }
public string EmployeeAddress { get; set; }
public string EmployeePosition { get; set; }
public DateTime EmployeeBirthday { get; set; }
}
}

3.2  DBHelper帮助类

 using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI.WebControls; namespace MVCCrud.Areas.DBUtility
{
public abstract class DbHelperSQL
{
/*
* content:DbHelper帮助类
*author:Alan_beijing
* date:2017-10-01
*/
public DbHelperSQL()
{
//构造函数
}
protected static string ConnectionString = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
protected static SqlConnection Connection;
//定义数据库的打开和关闭方法
protected static void Open()
{
if (Connection == null)
{
Connection = new SqlConnection(ConnectionString);
}
if (Connection.State.Equals(ConnectionState.Closed))
{
Connection.Open();
}
}
protected static void Close()
{
if (Connection != null)
{
Connection.Close();
}
} // 公有方法,获取数据,返回一个DataSet。
public static DataSet GetDataSet(string SqlString)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(SqlString, connection))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
connection.Close();
return ds;
}
}
}
}
// 公有方法,获取数据,返回一个DataTable。
public static DataTable GetDataTable(string SqlString)
{
DataSet dataset = GetDataSet(SqlString);
return dataset.Tables[];
}
public static int ExecuteSQL(String SqlString, Hashtable MyHashTb)
{
int count = -;
SqlConnection connectiontemp = new SqlConnection(ConnectionString);
connectiontemp.Open();
try
{
SqlCommand cmd = new SqlCommand(SqlString, connectiontemp);
foreach (DictionaryEntry item in MyHashTb)
{
string[] CanShu = item.Key.ToString().Split('|');
if (CanShu[].ToString().Trim() == "string")
{
cmd.Parameters.Add(CanShu[], SqlDbType.VarChar);
}
else if (CanShu[].ToString().Trim() == "int")
{
cmd.Parameters.Add(CanShu[], SqlDbType.Int);
}
else if (CanShu[].ToString().Trim() == "text")
{
cmd.Parameters.Add(CanShu[], SqlDbType.Text);
}
else if (CanShu[].ToString().Trim() == "datetime")
{
cmd.Parameters.Add(CanShu[], SqlDbType.DateTime);
}
else
{
cmd.Parameters.Add(CanShu[], SqlDbType.VarChar);
}
cmd.Parameters[CanShu[]].Value = item.Value.ToString();
}
count = cmd.ExecuteNonQuery();
}
catch
{
count = -;
}
finally
{
connectiontemp.Close();
}
return count;
}
// 公有方法,执行Sql语句。对Update、Insert、Delete为影响到的行数,其他情况为-1
public static int ExecuteSQL(String SqlString)
{
int count = -;
SqlConnection connectionTemp = new SqlConnection(ConnectionString);
connectionTemp.Open();
try
{
SqlCommand cmd = new SqlCommand(SqlString, connectionTemp);
count = cmd.ExecuteNonQuery();
}
catch
{
count = -;
}
finally
{
connectionTemp.Close();
}
return count;
}
// 公有方法,执行一组Sql语句。返回是否成功,采用事务管理,发现异常时回滚数据
public static bool ExecuteSQL(string[] SqlStrings)
{
bool success = true;
SqlConnection connectionTemp = new SqlConnection(ConnectionString);
connectionTemp.Open();
SqlCommand cmd = new SqlCommand();
SqlTransaction trans = Connection.BeginTransaction();
cmd.Connection = connectionTemp;
cmd.Transaction = trans;
try
{
foreach (string str in SqlStrings)
{
cmd.CommandText = str;
cmd.ExecuteNonQuery();
}
trans.Commit();
}
catch
{
success = false;
trans.Rollback();
}
finally
{
connectionTemp.Close();
}
return success;
}
// 执行一条计算查询结果语句,返回查询结果(object)。
public static object GetSingle(string SQLString)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
connection.Close();
return null;
}
else
{
connection.Close();
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
return null;
//throw e;
}
}
}
}
public static object GetSingle(string SQLString, int Times)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
connection.Close();
return null;
}
else
{
connection.Close();
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
//throw e;
return null;
}
}
}
}
public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
connection.Close();
return null;
}
else
{
connection.Close();
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
//throw e;
return null;
}
}
}
}
// 执行SQL语句,返回影响的记录数
public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
connection.Close();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
//throw e;
return ;
}
}
}
}
//执行查询语句,返回DataSet
public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear(); }
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
connection.Close();
return ds;
}
}
}
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
}
}
}

4   数据访问层DAL

4.1  对EmployeeInfo的CRUD

 using MVCCrud.Areas.DBUtility;
using MVCCrud.Areas.JqGridDemo.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web; namespace MVCCrud.Areas.DAL
{
public class EmployeeInfoToCRUD
{
/// <summary>
/// 增加一条数据
/// </summary>
/// <param name="employeeInfo">EmployeeInfo对象</param>
/// <returns>添加数据是否成功</returns>
public int DALEmployeeInfoToDdd(EmployeeInfo employeeInfo)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("insert into EmployeeInfo(");
strSql.Append("EmployeeID,EmployeeName,EmployeeMajor,EmployeeDepartment,EmployeeTel,EmployeeEmail,EmployeeJiGuan,EmployeeAddress,EmployeePosition,EmployeeBirthday)");
strSql.Append(" values (");
strSql.Append("@EmployeeID,@EmployeeName,@EmployeeMajor,@EmployeeDepartment,@EmployeeTel,@EmployeeEmail,@EmployeeJiGuan,@EmployeeAddress,@EmployeePosition,@EmployeeBirthday)");
strSql.Append(";select @@IDENTITY");
SqlParameter[] parameters =
{
new SqlParameter("@EmployeeID", SqlDbType.VarChar,),
new SqlParameter("@EmployeeName", SqlDbType.VarChar,),
new SqlParameter("@EmployeeMajor", SqlDbType.Text),
new SqlParameter("@EmployeeDepartment",SqlDbType.VarChar,),
new SqlParameter("@EmployeeTel", SqlDbType.VarChar,),
new SqlParameter("@EmployeeEmail", SqlDbType.VarChar,),
new SqlParameter("@EmployeeJiGuan", SqlDbType.VarChar,),
new SqlParameter("@EmployeeAddress", SqlDbType.VarChar,),
new SqlParameter("@EmployeePosition", SqlDbType.VarChar, ),
new SqlParameter("@EmployeeBirthday", SqlDbType.DateTime)
}; parameters[].Value = employeeInfo.EmployeeID;
parameters[].Value = employeeInfo.EmployeeName;
parameters[].Value = employeeInfo.EmployeeMajor;
parameters[].Value = employeeInfo.EmployeeDepartment;
parameters[].Value = employeeInfo.EmployeeTel;
parameters[].Value = employeeInfo.EmployeeEmail;
parameters[].Value = employeeInfo.EmployeeJiGuan;
parameters[].Value = employeeInfo.EmployeeAddress;
parameters[].Value = employeeInfo.EmployeePosition;
parameters[].Value = employeeInfo.EmployeeBirthday; object obj = DbHelperSQL.GetSingle(strSql.ToString(), parameters);
if (obj == null)
{
return ;
}
else
{
return Convert.ToInt32(obj);
}
} /// <summary>
/// 删除一条数据
/// </summary>
/// <param name="employeeID">查询参数:员工ID</param>
/// <returns>是否成功删除</returns>
public int DALEmployeeInfoToDelete(string employeeID)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("DELETE EmployeeInfo");
strSql.Append(" WHERE EmployeeID=@EmployeeID ");
SqlParameter[] parameters = {
new SqlParameter("@EmployeeID",SqlDbType.VarChar,)};
parameters[].Value = employeeID; return DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
} /// <summary>
/// 获取EmployeeInfo数据表
/// </summary>
/// <returns>返回EmployeeInfo数据表</returns>
public DataTable DALEmployeeInfoToGetTable()
{
StringBuilder strSql = new StringBuilder();
strSql.Append("SELECT * FROM EmployeeInfo ");
return DbHelperSQL.GetDataTable(strSql.ToString());
} /// <summary>
/// 根据EmployeeName查询EmployeeInfo实体表数据
/// </summary>
/// <param name="EmployeeName">查询参数:EmployeeName</param>
/// <returns>返回查询到的DataTable</returns>
public DataTable DALEmployeeInfoToGetTable(string EmployeeName)
{
string strSql = @"SELECT * FROM EmployeeInfo WHERE EmployeeName=@EmployeeName";
SqlParameter[] parameters = {
new SqlParameter("@EmployeeName",SqlDbType.VarChar,)
};
parameters[].Value = EmployeeName;
return DbHelperSQL.Query(strSql, parameters).Tables["ds"];
}
/// <summary>
/// 根据employeeInfo条件更新数据
/// </summary>
/// <param name="employeeInfo">更新条件:employeeInfo</param>
public void DALEmployeeInfoToUpdate(EmployeeInfo employeeInfo)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("UPDATE EmployeeInfo SET ");
strSql.Append("EmployeeName=@EmployeeName,EmployeeMajor=@EmployeeMajor,");
strSql.Append("EmployeeDepartment=@EmployeeDepartment,EmployeeTel=@EmployeeTel,EmployeeEmail=@EmployeeEmail,");
strSql.Append("EmployeeJiGuan=@EmployeeJiGuan,EmployeeAddress=@EmployeeAddress,EmployeePosition=@EmployeePosition,EmployeeBirthday=@EmployeeBirthday");
strSql.Append(" WHERE EmployeeID=@EmployeeID");
SqlParameter[] parameters = {
new SqlParameter("@EmployeeID", SqlDbType.VarChar,),
new SqlParameter("@EmployeeName", SqlDbType.VarChar,),
new SqlParameter("@EmployeeMajor", SqlDbType.Text),
new SqlParameter("@EmployeeDepartment",SqlDbType.VarChar,),
new SqlParameter("@EmployeeTel", SqlDbType.VarChar,),
new SqlParameter("@EmployeeEmail", SqlDbType.VarChar,),
new SqlParameter("@EmployeeJiGuan", SqlDbType.VarChar,),
new SqlParameter("@EmployeeAddress", SqlDbType.VarChar,),
new SqlParameter("@EmployeePosition", SqlDbType.VarChar, ),
new SqlParameter("@EmployeeBirthday", SqlDbType.DateTime)
};
parameters[].Value = employeeInfo.EmployeeID;
parameters[].Value = employeeInfo.EmployeeName;
parameters[].Value = employeeInfo.EmployeeMajor;
parameters[].Value = employeeInfo.EmployeeDepartment;
parameters[].Value = employeeInfo.EmployeeTel;
parameters[].Value = employeeInfo.EmployeeEmail;
parameters[].Value = employeeInfo.EmployeeJiGuan;
parameters[].Value = employeeInfo.EmployeeAddress;
parameters[].Value = employeeInfo.EmployeePosition;
parameters[].Value = employeeInfo.EmployeeBirthday; DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
}
}
}

4.2 简要分析

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

5   控制器层

5.1 方法

 using MVCCrud.Areas.JqGridDemo.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCCrud.Areas.DAL; namespace MVCCrud.Areas.JqGridDemo.Controllers
{
public class JqGridCRUDController : Controller
{
// GET: JqGridDemo/JqGridCRUD
//初始视图表
public ActionResult Index()
{
return View();
}
//导入模板
public ActionResult GetEmployeeInfoTemple()
{
string path = Server.MapPath(@"~/Content/Upload/");
string fileName = "EmployeeImport.xlsx";
return File(new FileStream(path + fileName, FileMode.Open, FileAccess.Read), "xls", fileName);
} //预设置初始化数据表
public ActionResult EmployeeInfoToLoad()
{
List<EmployeeInfo> ltPI = new List<EmployeeInfo>();
EmployeeInfoToCRUD employeeInfoToCRUD = new EmployeeInfoToCRUD();
DataTable dt = employeeInfoToCRUD.DALEmployeeInfoToGetTable();
for (int i = ; i < dt.Rows.Count; i++)
{
EmployeeInfo custInfo = new EmployeeInfo();
custInfo.EmployeeID = dt.Rows[i]["EmployeeID"].ToString();
custInfo.EmployeeName = dt.Rows[i]["EmployeeName"].ToString();
custInfo.EmployeeMajor = dt.Rows[i]["EmployeeMajor"].ToString();
custInfo.EmployeeDepartment = dt.Rows[i]["EmployeeDepartment"].ToString();
custInfo.EmployeeTel = dt.Rows[i]["EmployeeTel"].ToString();
custInfo.EmployeeEmail = dt.Rows[i]["EmployeeEmail"].ToString();
custInfo.EmployeeJiGuan = dt.Rows[i]["EmployeeJiGuan"].ToString();
custInfo.EmployeeAddress = dt.Rows[i]["EmployeeAddress"].ToString();
custInfo.EmployeePosition = dt.Rows[i]["EmployeePosition"].ToString();
if (dt.Rows[i]["EmployeeBirthday"] != System.DBNull.Value)
{
custInfo.EmployeeBirthday = Convert.ToDateTime(dt.Rows[i]["EmployeeBirthday"]);
}
ltPI.Add(custInfo);
TempData["CustomerInfo"] = ltPI;
}
return Content(ToJsonString(ltPI));
} //预设置添加数据
public void EmployeeInfoToDdd(EmployeeInfo employeeInfo)
{
EmployeeInfoToCRUD employeeInfoToCRUD = new EmployeeInfoToCRUD();
employeeInfoToCRUD.DALEmployeeInfoToDdd(employeeInfo);
}
//预设置删除数据
[HttpPost]
public void EmployeeInfoToDel(string EmployeeID)
{
EmployeeInfoToCRUD employeeInfoToCRUD = new EmployeeInfoToCRUD();
employeeInfoToCRUD.DALEmployeeInfoToDelete(EmployeeID);
} //预设置更新数据
public void EmployeeInfoToUpdate(EmployeeInfo employeeInfo)
{
EmployeeInfoToCRUD employeeInfoToCRUD = new EmployeeInfoToCRUD();
employeeInfoToCRUD.DALEmployeeInfoToUpdate(employeeInfo);
} //预设置查询数据
public ActionResult EmployeeInfoToSearch(string employeeName)
{
List<EmployeeInfo> ltPI = new List<EmployeeInfo>();
EmployeeInfoToCRUD employeeInfoToCRUD = new EmployeeInfoToCRUD();
DataTable dt = employeeInfoToCRUD.DALEmployeeInfoToGetTable(employeeName);
for (int i = ; i < dt.Rows.Count; i++)
{
EmployeeInfo custInfo = new EmployeeInfo();
custInfo.EmployeeID = dt.Rows[i]["EmployeeID"].ToString();
custInfo.EmployeeName = dt.Rows[i]["EmployeeName"].ToString();
custInfo.EmployeeMajor = dt.Rows[i]["EmployeeMajor"].ToString();
custInfo.EmployeeDepartment = dt.Rows[i]["EmployeeDepartment"].ToString();
custInfo.EmployeeTel = dt.Rows[i]["EmployeeTel"].ToString();
custInfo.EmployeeEmail = dt.Rows[i]["EmployeeEmail"].ToString();
custInfo.EmployeeJiGuan = dt.Rows[i]["EmployeeJiGuan"].ToString();
custInfo.EmployeeAddress = dt.Rows[i]["EmployeeAddress"].ToString();
custInfo.EmployeePosition = dt.Rows[i]["EmployeePosition"].ToString();
if (dt.Rows[i]["EmployeeBirthday"] != System.DBNull.Value)
{
custInfo.EmployeeBirthday = Convert.ToDateTime(dt.Rows[i]["EmployeeBirthday"]);
}
ltPI.Add(custInfo);
TempData["CustomerInfo"] = ltPI;
}
return Content(ToJsonString(ltPI));
} /// <summary>
/// 为Oject对象增加ToJsonString方法(注意对项目添加Newtonsoft.Json.dll引用)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public string ToJsonString(Object obj)
{
JsonSerializerSettings jsSettings = new JsonSerializerSettings();
jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
return JsonConvert.SerializeObject(obj, jsSettings);
}
}
}

5.2 分析

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

6   展示层

6.1  View  Code

 @{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/OuterLibrary/jquery-ui-themes-1.12.1/jquery-ui.css" rel="stylesheet" />
<link href="~/OuterLibrary/Guriddo_jqGrid_JS_5.2.1/src/css/ui.jqgrid.css" rel="stylesheet" />
<script src="~/OuterLibrary/Guriddo_jqGrid_JS_5.2.1/js/jquery-1.11.0.min.js"></script>
<script src="~/OuterLibrary/Guriddo_jqGrid_JS_5.2.1/src/jquery.jqGrid.js"></script>
<script src="//apps.bdimg.com/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="~/OuterLibrary/tonytomov-jqGrid-6659334/js/i18n/grid.locale-cn.js"></script>
<script type="text/javascript" language="javascript" src="//cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
<script src="~/OuterLibrary/Guriddo_jqGrid_JS_5.2.1/src/grid.export.js"></script>
<script src="~/OuterLibrary/Guriddo_jqGrid_JS_5.2.1/src/grid.import.js"></script>
<title>员工信息表</title>
<script type="text/javascript">
$(document).ready(function () {
//添加
$("#btn_add").click(function () {
//var model = jQuery("#JqGrid-table").jqGrid('getRowData', EmployeeID);
$("#AddEmployeeInfo").dialog({
height: ,
width: ,
resizable: false,
modal: true, //这里就是控制弹出为模态
buttons: {
"确定": function () {
//alert("在这里对数据进行修改!");
//$(this).dialog("close");
//var birthdayTime ="2017/9/28";
var employeeID = $("#ADD_EmployeeID").val();
var employeeName = $("#ADD_EmployeeName").val();
var employeeMajor = $("#ADD_EmployeeMajor").val();
var employeeDepartment = $("#ADD_EmployeeDepartment").val();
var employeeTel = $("#ADD_EmployeeTel").val();
var employeeEmail = $("#ADD_EmployeeEmail").val();
var employeeJiGuan = $("#ADD_EmployeeJiGuan").val();
var employeeAddress = $("#ADD_EmployeeAddress").val();
var employeePosition = $("#ADD_EmployeePosition").val();
var employeeBirthday = $("#ADD_EmployeeBirthday").val();
$.ajax({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToDdd",
type: "GET",
data: {
EmployeeID: employeeID, EmployeeName: employeeName, EmployeeMajor: employeeMajor,
EmployeeDepartment: employeeDepartment, EmployeeTel: employeeTel, EmployeeEmail: employeeEmail,
EmployeeJiGuan: employeeJiGuan, EmployeeAddress: employeeAddress, EmployeePosition: employeePosition,
EmployeeBirthday: employeeBirthday
},
success: function (message) {
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
page: ,
datatype: "json"
}).trigger("reloadGrid");
alert('添加数据成功'); },
error: function (message) {
alert('error!');
}
});
},
"取消": function () {
$(this).dialog("close");
}
}
});
});
//删除
$("#btn_del").click(function () {
var employeeID = $('#JqGrid-table').jqGrid('getGridParam', 'selrow');//获取行id
$.ajax({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToDel",
type: "post",
data: { EmployeeID: employeeID },
success: function (message) {
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
page: ,
datatype: "json"
}).trigger("reloadGrid");
alert('成功删除一条数据');
},
error: function (message) {
alert('error!');
}
});
});
//编辑
$("#btn_edit").click(function () {
//var ids = jQuery("#JqGrid-table").jqGrid('getDataIDs');//返回grid里所有数据的id
var id = jQuery("#JqGrid-table").jqGrid('getGridParam', 'selarrrow');
var EmployeeInfoModel = jQuery("#JqGrid-table").jqGrid('getRowData', id);
$("#Modify_EmployeeID").val(EmployeeInfoModel.EmployeeID);
$("#Modify_EmployeeName").val(EmployeeInfoModel.EmployeeName);
$("#Modify_EmployeeMajor").val(EmployeeInfoModel.EmployeeMajor);
$("#Modify_EmployeeDepartment").val(EmployeeInfoModel.EmployeeDepartment);
$("#Modify_EmployeeTel").val(EmployeeInfoModel.EmployeeTel);
$("#Modify_EmployeeEmail").val(EmployeeInfoModel.EmployeeEmail);
$("#Modify_EmployeeJiGuan").val(EmployeeInfoModel.EmployeeJiGuan);
$("#Modify_EmployeeAddress").val(EmployeeInfoModel.EmployeeAddress);
$("#Modify_EmployeePosition").val(EmployeeInfoModel.EmployeePosition);
$("#Modify_EmployeeBirthday").val(EmployeeInfoModel.EmployeeBirthday);
$("#ModifyEmployeeInfo").dialog({
height: ,
width: ,
resizable: false,
modal: true, //这里就是控制弹出为模态
buttons: {
"确定": function () {
//alert("在这里对数据进行修改!");
//$(this).dialog("close");
//var birthdayTime ="2017/9/28";
//$("#Modify_EmployeeEmployeeName").value = 'ddd';
//提交前的初始值
var employeeID = $("#Modify_EmployeeID").val();
var employeeName = $("#Modify_EmployeeName").val();
var employeeMajor = $("#Modify_EmployeeMajor").val();
var employeeDepartment = $("#Modify_EmployeeDepartment").val();
var employeeTel = $("#Modify_EmployeeTel").val();
var employeeEmail = $("#Modify_EmployeeEmail").val();
var employeeJiGuan = $("#Modify_EmployeeJiGuan").val();
var employeeAddress = $("#Modify_EmployeeAddress").val();
var employeePosition = $("#Modify_EmployeePosition").val();
var employeeBirthday = $("#Modify_EmployeeBirthday").val();
$.ajax({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToUpdate",
type: "GET",
data: {
EmployeeID: employeeID, EmployeeName: employeeName, EmployeeMajor: employeeMajor,
EmployeeDepartment: employeeDepartment, EmployeeTel: employeeTel, EmployeeEmail: employeeEmail,
EmployeeJiGuan: employeeJiGuan, EmployeeAddress: employeeAddress, EmployeePosition: employeePosition,
EmployeeBirthday: employeeBirthday
},
success: function (message) {
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
page: ,
datatype: "json"
}).trigger("reloadGrid");
alert('编辑成功!!'); },
error: function (message) {
alert('error!');
}
});
},
"取消": function () {
$(this).dialog("close");
}
}
}); });
//查询
$("#btn_search").click(function () {
var employeeName = $("#precisionSearch_input").val();
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToSearch" + "?EmployeeName=" + employeeName,
page: ,
datatype: "json"
}).trigger("reloadGrid"); });
//导出
$("#btn_export").on("click", function () {
$("#JqGrid-table").jqGrid("exportToExcel", {
includeLabels: true,
includeGroupHeader: true,
includeFooter: true,
fileName: "jqGridExport.xlsx",
maxlength: // maxlength for visible string
});
});
//导入
$("#btn_import").click(function () {
var FileName = $("#UpLoadFile").val();
$.ajax({
url: '/JqGridDemo/ImportData/InsertDataToDB',
type: 'post',
data: { fileName: FileName }
});
});
})
</script>
</head>
<body>
<div>
<div>
<input id="UpLoadFile" type="file" />
<input id="btn_import" type="button" value="批量导入" class="btn btn-info" />
<a href="/JqGridDemo/JqGridCRUD/GetEmployeeInfoTemple">(点击此处下载模板)</a>
<label>模糊查询:</label> <input id="search_input" type="text" placeholder="模糊查询" />
<input id="precisionSearch_input" type="text" placeholder="请输入您要查询的姓名" />
<input id="btn_search" type="button" value="查询" class="btn btn-info" />
<input id="btn_add" type="button" value="添加" class="btn btn-primary" />
<input id="btn_edit" type="button" value="编辑" class="btn btn-success" />
<input id="btn_del" type="button" value="删除" class="btn btn-danger" />
<input id="btn_export" type="button" value="导出" class="btn btn-info" /> </div>
<div class="main" id="main">
<table id="JqGrid-table"></table>
<div id="JqGrid-pager"></div>
<div id="ModifyEmployeeInfo" title="修改员工信息" style="display:none;">
<table>
<tbody>
<tr>
<td>员工ID:<input type="text" id="Modify_EmployeeID" placeholder="请输入员工ID" /></td>
<td>员工姓名:<input type="text" id="Modify_EmployeeName" placeholder="请输入员工姓名" /></td>
</tr>
<tr>
<td>员工专业:<input type="text" id="Modify_EmployeeMajor" placeholder="请输入员工专业" /></td>
<td>员工部门:<input type="text" id="Modify_EmployeeDepartment" placeholder="请输入员工部门" /></td>
</tr>
<tr>
<td>员工电话:<input type="text" id="Modify_EmployeeTel" placeholder="请输入员工电话" /></td>
<td>员工邮件:<input type="text" id="Modify_EmployeeEmail" placeholder="请输入员工邮件" /></td>
</tr>
<tr>
<td>员工籍贯:<input type="text" id="Modify_EmployeeJiGuan" placeholder="请输入员工籍贯" /></td>
<td>员工住址:<input type="text" id="Modify_EmployeeAddress" placeholder="请输入员工住址" /></td>
</tr>
<tr>
<td>员工职位:<input type="text" id="Modify_EmployeePosition" placeholder="请输入员工职位" /></td>
<td>员工生日:<input type="text" id="Modify_EmployeeBirthday" placeholder="请输入员工生日" /></td>
</tr>
</tbody>
</table>
</div>
<div id="AddEmployeeInfo" title="修改员工信息" style="display:none;">
<table>
<tbody>
<tr>
<td>员工ID:<input type="text" id="ADD_EmployeeID" placeholder="请输入员工ID" /></td>
<td>员工姓名:<input type="text" id="ADD_EmployeeName" placeholder="请输入员工姓名" /></td>
</tr>
<tr>
<td>员工专业:<input type="text" id="ADD_EmployeeMajor" placeholder="请输入员工专业" /></td>
<td>员工部门:<input type="text" id="ADD_EmployeeDepartment" placeholder="请输入员工部门" /></td>
</tr>
<tr>
<td>员工电话:<input type="text" id="ADD_EmployeeTel" placeholder="请输入员工电话" /></td>
<td>员工邮件:<input type="text" id="ADD_EmployeeEmail" placeholder="请输入员工邮件" /></td>
</tr>
<tr>
<td>员工籍贯:<input type="text" id="ADD_EmployeeJiGuan" placeholder="请输入员工籍贯" /></td>
<td>员工住址:<input type="text" id="ADD_EmployeeAddress" placeholder="请输入员工住址" /></td>
</tr>
<tr>
<td>员工职位:<input type="text" id="ADD_EmployeePosition" placeholder="请输入员工职位" /></td>
<td>员工生日:<input type="text" id="ADD_EmployeeBirthday" placeholder="请输入员工生日" value="2014/03/01" /></td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#JqGrid-table").jqGrid({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
//editurl: 'clientArray',
datatype: "json",
height: ,
mtype: "Get",
colNames: ['员工ID', '员工姓名', '员工专业', '员工部门', '员工电话', '员工邮件', '员工籍贯', '员工住址', '员工职位', '员工生日'],
colModel: [{
name: 'EmployeeID',
index: 'EmployeeID',
key: true,
width: ,
edittype: Text,
editable: true,
editoptions: {
size: "",
maxlength: "",
sorttable: false,
},
searchoptions: {
searchOperMenu: false,
sopt: ['eq', 'gt', 'lt', 'ge', 'le']
}
}, {
name: 'EmployeeName',
index: 'EmployeeName',
width: ,
editable: true,
editoptions: {
size: "",
maxlength: "",
sortable: true
}
}, {
name: 'EmployeeMajor',
index: 'EmployeeMajor',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
},
{
name: 'EmployeeDepartment',
index: 'EmployeeDepartment',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeTel',
index: 'EmployeeTel',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeEmail',
index: 'EmployeeEmail',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeJiGuan',
index: 'EmployeeJiGuan',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeAddress',
index: 'EmployeeAddress',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeePosition',
index: 'EmployeePosition',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeBirthday',
index: 'EmployeeBirthday',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}],
viewrecords: true,
rowNum: ,
rowList: [, , , ],
pager: '#JqGrid-pager',
altRows: true,
multiselect: true,
multiboxonly: true,
caption: "员工信息表",
autowidth: true,
//width: "100%",
height: Audio,
sortable: true,
sortorder: 'asc',
loadonce: true, //排序时,必须添加该字段
})
//JqGrid自带的CRUD
$('#JqGrid-table').jqGrid('navGrid', "#JqGrid-pager", {
search: true, // show search button on the toolbar
add: true,
edit: true,
del: true,
refresh: true
});
//模糊查询
var timer;
$("#search_input").on("keyup", function () {
var self = this;
if (timer) { clearTimeout(timer); }
timer = setTimeout(function () {
//timer = null;
$("#JqGrid-table").jqGrid('filterInput', self.value);
}, );
});
})
</script>
</div>
</body>
</html>

6.2  分析

6.2.1  初始化数据

(1)图解功能

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

(2)功能Code

定义table获取区和翻页区

 <table id="JqGrid-table"></table>
<div id="JqGrid-pager"></div>

JqGrid

  <script type="text/javascript">
$(document).ready(function () {
$("#JqGrid-table").jqGrid({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
//editurl: 'clientArray',
datatype: "json",
height: ,
mtype: "Get",
colNames: ['员工ID', '员工姓名', '员工专业', '员工部门', '员工电话', '员工邮件', '员工籍贯', '员工住址', '员工职位', '员工生日'],
colModel: [{
name: 'EmployeeID',
index: 'EmployeeID',
key: true,
width: ,
edittype: Text,
editable: true,
editoptions: {
size: "",
maxlength: "",
sorttable: false,
},
searchoptions: {
searchOperMenu: false,
sopt: ['eq', 'gt', 'lt', 'ge', 'le']
}
}, {
name: 'EmployeeName',
index: 'EmployeeName',
width: ,
editable: true,
editoptions: {
size: "",
maxlength: "",
sortable: true
}
}, {
name: 'EmployeeMajor',
index: 'EmployeeMajor',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
},
{
name: 'EmployeeDepartment',
index: 'EmployeeDepartment',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeTel',
index: 'EmployeeTel',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeEmail',
index: 'EmployeeEmail',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeJiGuan',
index: 'EmployeeJiGuan',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeAddress',
index: 'EmployeeAddress',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeePosition',
index: 'EmployeePosition',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeBirthday',
index: 'EmployeeBirthday',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}],
viewrecords: true,
rowNum: ,
rowList: [, , , ],
pager: '#JqGrid-pager',
altRows: true,
multiselect: true,
multiboxonly: true,
caption: "员工信息表",
autowidth: true,
//width: "100%",
height: Audio,
sortable: true,
sortorder: 'asc',
loadonce: true, //排序时,必须添加该字段
})
})
</script>

6.2.2  JqGrid自带的CRUD

(1)图解功能

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

(2)功能Code

 //JqGrid自带的CRUD
$('#JqGrid-table').jqGrid('navGrid', "#JqGrid-pager", {
search: true, // show search button on the toolbar
add: true,
edit: true,
del: true,
refresh: true
});

6.2.3 自动检测区:

(1)图解功能

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

(1)功能Code

 //模糊查询
var timer;
$("#search_input").on("keyup", function () {
var self = this;
if (timer) { clearTimeout(timer); }
timer = setTimeout(function () {
//timer = null;
$("#JqGrid-table").jqGrid('filterInput', self.value);
}, );
});

6.2.4  JqGrid自带导出功能

(1)图解功能

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

(2)功能Code

$("#btn_export").on("click", function () {
$("#JqGrid-table").jqGrid("exportToExcel", {
includeLabels: true,
includeGroupHeader: true,
includeFooter: true,
fileName: "jqGridExport.xlsx",
maxlength: // maxlength for visible string
});
});

6.2.5 自定义CRUD

(1)图解功能

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

(2)功能Code

 <script type="text/javascript">
$(document).ready(function () {
//添加
$("#btn_add").click(function () {
//var model = jQuery("#JqGrid-table").jqGrid('getRowData', EmployeeID);
$("#AddEmployeeInfo").dialog({
height: ,
width: ,
resizable: false,
modal: true, //这里就是控制弹出为模态
buttons: {
"确定": function () {
//alert("在这里对数据进行修改!");
//$(this).dialog("close");
//var birthdayTime ="2017/9/28";
var employeeID = $("#ADD_EmployeeID").val();
var employeeName = $("#ADD_EmployeeName").val();
var employeeMajor = $("#ADD_EmployeeMajor").val();
var employeeDepartment = $("#ADD_EmployeeDepartment").val();
var employeeTel = $("#ADD_EmployeeTel").val();
var employeeEmail = $("#ADD_EmployeeEmail").val();
var employeeJiGuan = $("#ADD_EmployeeJiGuan").val();
var employeeAddress = $("#ADD_EmployeeAddress").val();
var employeePosition = $("#ADD_EmployeePosition").val();
var employeeBirthday = $("#ADD_EmployeeBirthday").val();
$.ajax({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToDdd",
type: "GET",
data: {
EmployeeID: employeeID, EmployeeName: employeeName, EmployeeMajor: employeeMajor,
EmployeeDepartment: employeeDepartment, EmployeeTel: employeeTel, EmployeeEmail: employeeEmail,
EmployeeJiGuan: employeeJiGuan, EmployeeAddress: employeeAddress, EmployeePosition: employeePosition,
EmployeeBirthday: employeeBirthday
},
success: function (message) {
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
page: ,
datatype: "json"
}).trigger("reloadGrid");
alert('添加数据成功'); },
error: function (message) {
alert('error!');
}
});
},
"取消": function () {
$(this).dialog("close");
}
}
});
});
//删除
$("#btn_del").click(function () {
var employeeID = $('#JqGrid-table').jqGrid('getGridParam', 'selrow');//获取行id
$.ajax({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToDel",
type: "post",
data: { EmployeeID: employeeID },
success: function (message) {
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
page: ,
datatype: "json"
}).trigger("reloadGrid");
alert('成功删除一条数据');
},
error: function (message) {
alert('error!');
}
});
});
//编辑
$("#btn_edit").click(function () {
//var ids = jQuery("#JqGrid-table").jqGrid('getDataIDs');//返回grid里所有数据的id
var id = jQuery("#JqGrid-table").jqGrid('getGridParam', 'selarrrow');
var EmployeeInfoModel = jQuery("#JqGrid-table").jqGrid('getRowData', id);
$("#Modify_EmployeeID").val(EmployeeInfoModel.EmployeeID);
$("#Modify_EmployeeName").val(EmployeeInfoModel.EmployeeName);
$("#Modify_EmployeeMajor").val(EmployeeInfoModel.EmployeeMajor);
$("#Modify_EmployeeDepartment").val(EmployeeInfoModel.EmployeeDepartment);
$("#Modify_EmployeeTel").val(EmployeeInfoModel.EmployeeTel);
$("#Modify_EmployeeEmail").val(EmployeeInfoModel.EmployeeEmail);
$("#Modify_EmployeeJiGuan").val(EmployeeInfoModel.EmployeeJiGuan);
$("#Modify_EmployeeAddress").val(EmployeeInfoModel.EmployeeAddress);
$("#Modify_EmployeePosition").val(EmployeeInfoModel.EmployeePosition);
$("#Modify_EmployeeBirthday").val(EmployeeInfoModel.EmployeeBirthday);
$("#ModifyEmployeeInfo").dialog({
height: ,
width: ,
resizable: false,
modal: true, //这里就是控制弹出为模态
buttons: {
"确定": function () {
//alert("在这里对数据进行修改!");
//$(this).dialog("close");
//var birthdayTime ="2017/9/28";
//$("#Modify_EmployeeEmployeeName").value = 'ddd';
//提交前的初始值
var employeeID = $("#Modify_EmployeeID").val();
var employeeName = $("#Modify_EmployeeName").val();
var employeeMajor = $("#Modify_EmployeeMajor").val();
var employeeDepartment = $("#Modify_EmployeeDepartment").val();
var employeeTel = $("#Modify_EmployeeTel").val();
var employeeEmail = $("#Modify_EmployeeEmail").val();
var employeeJiGuan = $("#Modify_EmployeeJiGuan").val();
var employeeAddress = $("#Modify_EmployeeAddress").val();
var employeePosition = $("#Modify_EmployeePosition").val();
var employeeBirthday = $("#Modify_EmployeeBirthday").val();
$.ajax({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToUpdate",
type: "GET",
data: {
EmployeeID: employeeID, EmployeeName: employeeName, EmployeeMajor: employeeMajor,
EmployeeDepartment: employeeDepartment, EmployeeTel: employeeTel, EmployeeEmail: employeeEmail,
EmployeeJiGuan: employeeJiGuan, EmployeeAddress: employeeAddress, EmployeePosition: employeePosition,
EmployeeBirthday: employeeBirthday
},
success: function (message) {
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
page: ,
datatype: "json"
}).trigger("reloadGrid");
alert('编辑成功!!'); },
error: function (message) {
alert('error!');
}
});
},
"取消": function () {
$(this).dialog("close");
$("#JqGrid-table").jqGrid('clearGridData');
//$("#JqGrid-table").trigger('reloadGrid');
$("#JqGrid-table").setGridParam({ url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad" }).trigger('reloadGrid');
}
}
}); });
//查询
$("#btn_search").click(function () {
var employeeName = $("#precisionSearch_input").val();
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToSearch" + "?EmployeeName=" + employeeName,
page: ,
datatype: "json"
}).trigger("reloadGrid"); });
//导出
$("#btn_export").on("click", function () {
$("#JqGrid-table").jqGrid("exportToExcel", {
includeLabels: true,
includeGroupHeader: true,
includeFooter: true,
fileName: "jqGridExport.xlsx",
maxlength: // maxlength for visible string
});
});
//导入
$("#btn_import").click(function () {
var FileName = $("#UpLoadFile").val();
$.ajax({
url: '/JqGridDemo/ImportData/InsertDataToDB',
type: 'post',
data: { fileName: FileName }
});
});
})
</script>

6.2.6 导出

(1)图解功能

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

(2)功能Code

 using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace MVCCrud.Areas.JqGridDemo.Controllers
{
public class ImportDataController : Controller
{
// GET: JqGridDemo/ImportData
public ActionResult Index()
{
return View();
} /// <summary>
/// 从excel读取数据
/// </summary>
/// <param name="filepath">excel文件路径</param>
/// <returns></returns>
public static DataSet ReadExcel(string FilePath)
{
try
{
string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", FilePath);
using (OleDbConnection OleDbConn = new OleDbConnection(strConn))
{
OleDbConn.Open();
string sql = "SELECT * FROM [Sheet1$]";
OleDbDataAdapter OleDbDA = new OleDbDataAdapter(sql, OleDbConn);
DataSet OleDS = new DataSet();
OleDbDA.Fill(OleDS, "ExcelToTalbe");
return OleDS;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 将excel数据插入到EmployeeName表中
/// </summary>
/// <param name="fileName">excel文件所在路径</param>
public void InsertDataToDB(string fileName)
{
//fileName = @"E:\testData.xls";
if (!System.IO.File.Exists(fileName))
{
throw new Exception("指定路径的Excel文件不存在!");
}
DataSet ds = ReadExcel(fileName);
List<string> ListData = (from DataRow row in ds.Tables["ExcelToTalbe"].Rows select String.Format("INSERT INTO EmployeeInfo(EmployeeID,EmployeeName,EmployeeMajor,EmployeeDepartment,EmployeeTel,EmployeeEmail, EmployeeJiGuan,EmployeeAddress,EmployeePosition,EmployeeBirthday) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')", row[], row[], row[], row[], row[], row[], row[], row[], row[], row[])).ToList();
string ConStr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
SqlConnection conn = new SqlConnection(ConStr);
conn.Open();
foreach (string item in ListData)
{
SqlCommand comn = new SqlCommand(item, conn);
comn.ExecuteNonQuery();
}
}
}
}

7   问题区

Q1:批量导入时,excel版本问题

Q2:批量导入时,input 上传文件路径,需要使用相对路径,而非绝对路劲

8   待解决问题

Q1:统一异常控制

Q2:JqGrid换肤

Q3:压力测试

Q4:友好提示

Q4:其他

9   最后

首先祝福大家国庆快乐,除此之外,若有任何问题,欢迎指教。

10   参考文献

[01]http://www.trirand.com/blog/?page_id=5

[02]http://blog.mn886.net/jqGrid/

11  服务区

有喜欢的朋友,可以看一下,不喜欢的的朋友,勿喷,谢谢!!

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

12  版权

  • 感谢您的阅读,若有不足之处,欢迎指教,共同学习、共同进步。
  • 博主网址:http://www.cnblogs.com/wangjiming/。
  • 极少部分文章利用读书、参考、引用、抄袭、复制和粘贴等多种方式整合而成的,大部分为原创。
  • 如您喜欢,麻烦推荐一下;如您有新想法,欢迎提出,邮箱:2098469527@qq.com。
  • 可以转载该博客,但必须著名博客来源。
上一篇:背景建模SACON


下一篇:Swift Package Manager(一)初探